Skip to content

Commit

Permalink
feat: add chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 31, 2019
1 parent 0994580 commit 3742dac
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/chunk.ts
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
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export { default as base64UrlDecode } from './base64UrlDecode'
export { default as base64UrlEncode } from './base64UrlEncode'
export { default as bindEvent } from './bindEvent'
export { default as castArray } from './castArray'
export { default as chunk } from './chunk'
export { default as clamp } from './clamp'
export { default as defaultValue } from './defaultValue'
export { default as endsWith } from './endsWith'
Expand Down
9 changes: 9 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1582,3 +1582,12 @@ describe('formatDateDiff', () => {
})
})
})

describe('chunk', () => {
test('ok', () => {
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]])
expect(vtils.chunk([1, 2, 3], 2, 4)).toEqual([[1, 2], [3, 4]])
})
})

0 comments on commit 3742dac

Please sign in to comment.