Skip to content

Commit

Permalink
feat(utils): chunkEqual 新增 consistent 选项
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Feb 2, 2024
1 parent 6859e1e commit ddeb341
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/utils/__snapshots__/chunkEqual.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`chunkEqual consistent 1`] = `
Array [
Array [
1,
2,
100,
],
]
`;

exports[`chunkEqual 表现正常 1`] = `Array []`;

exports[`chunkEqual 表现正常 2`] = `
Expand Down
4 changes: 4 additions & 0 deletions src/utils/chunkEqual.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ describe('chunkEqual', () => {
expect(chunkEqual([1, 2, 3, 4, 5, 6], 3, () => 100)).toMatchSnapshot()
expect(chunkEqual([1, 2, 3, 4, 5, 6], 2, () => 100)).toMatchSnapshot()
})

test('consistent', () => {
expect(chunkEqual([1, 2], 3, () => 100, true)).toMatchSnapshot()
})
})
4 changes: 3 additions & 1 deletion src/utils/chunkEqual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,17 @@ import { chunk } from 'lodash-uni'
* @param array 数组
* @param size 分组大小
* @param filler 填充值
* @param consistent 是否保持一致性,默认 false,设为 true 则当数组长度小于分组大小时也填充数组使其长度达到分组大小
*/
export function chunkEqual<T>(
array: T[],
size: number,
filler: (index: number) => T,
consistent = false,
): T[][] {
const len = array.length
const remain = len % size
if (remain !== 0 && size < array.length) {
if (remain !== 0 && (consistent ? true : size < array.length)) {
array = array.slice()
for (let i = 0, n = size - remain; i < n; i++) {
array.push(filler(len + i))
Expand Down

0 comments on commit ddeb341

Please sign in to comment.