-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/** | ||
* 将 `array` 拆分成多个 `size` 长度的区块,并将它们组合成一个新数组返回。 | ||
* 如果 `array` 无法等分,且设置了 `filler`,剩余的元素将被 `filler` 填充。 | ||
* | ||
* @param array 要处理的数组 | ||
* @param size 每个区块的长度,最小为 1 | ||
* @param [filler] 填充物 | ||
* @returns 拆分后的新数组 | ||
*/ | ||
export default function chunk<T, F = never>(array: T[], size: number, filler?: F): (T | F)[][] { | ||
size = Math.max(size, 1) | ||
const result: (T | F)[][] = [] | ||
const rows = Math.ceil(array.length / size) | ||
for (let i = 0; i < rows; i++) { | ||
result.push(array.slice(i * size, (i + 1) * size)) | ||
} | ||
const lastRow = result[rows - 1] | ||
if (arguments.length === 3 && lastRow.length < size) { | ||
for (let i = 0, len = size - lastRow.length; i < len; i++) { | ||
lastRow.push(filler) | ||
} | ||
} | ||
return result | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters