Skip to content

Commit

Permalink
feat(chunk): filler can be a function
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Apr 10, 2019
1 parent 61046f2 commit 8451f6c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/chunk.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isFunction } from './isFunction'

/**
* 将 `array` 拆分成多个 `size` 长度的区块,并将它们组合成一个新数组返回。
* 如果 `array` 无法等分,且设置了 `filler`,剩余的元素将被 `filler` 填充。
Expand All @@ -7,7 +9,7 @@
* @param [filler] 填充物
* @returns 拆分后的新数组
*/
export function chunk<T, F = never>(array: T[], size: number, filler?: F): (T | F)[][] {
export function chunk<T, F = never>(array: T[], size: number, filler?: ((index: number) => F) | F): (T | F)[][] {
size = Math.max(size, 1)
const result: (T | F)[][] = []
const rows = Math.ceil(array.length / size)
Expand All @@ -16,8 +18,11 @@ export function chunk<T, F = never>(array: T[], size: number, filler?: F): (T |
}
const lastRow = result[rows - 1]
if (arguments.length === 3 && lastRow.length < size) {
const fillerIsFunction = isFunction(filler)
for (let i = 0, len = size - lastRow.length; i < len; i++) {
lastRow.push(filler)
lastRow.push(
fillerIsFunction ? (filler as any)(i) : filler,
)
}
}
return result
Expand Down
3 changes: 3 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1581,7 +1581,10 @@ describe('chunk', () => {
expect(vtils.chunk([1, 2], 0)).toEqual([[1], [2]])
expect(vtils.chunk([1, 2], 1)).toEqual([[1], [2]])
expect(vtils.chunk([1, 2, 3], 2)).toEqual([[1, 2], [3]])
})
test('filler ok', () => {
expect(vtils.chunk([1, 2, 3], 2, 4)).toEqual([[1, 2], [3, 4]])
expect(vtils.chunk([1, 2, 3], 2, index => index)).toEqual([[1, 2], [3, 0]])
})
})

Expand Down

0 comments on commit 8451f6c

Please sign in to comment.