Skip to content

Commit

Permalink
Adding chunked to array
Browse files Browse the repository at this point in the history
  • Loading branch information
kamaal111 committed Sep 2, 2024
1 parent eb0b6af commit 9a0c2af
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/arrays/chunked.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import chunked from './chunked';

describe('chunked', () => {
it.each([
{ input: [1], size: 0 },
{ input: [1, 2], size: 3 },
])('chunks default', ({ input, size }) => {
const result = chunked(input, size);

expect(result).toEqual([input]);
});

it.each([{ size: 0 }, { size: -1 }])('chunks empty input', ({ size }) => {
const result = chunked([], size);

expect(result).toEqual([]);
});

it.each([{ size: -3 }, { size: 0 }])(
'chunks zero or bellow size',
({ size }) => {
const input = [1, 2, 3, 4];

const result = chunked(input, size);

expect(result).toEqual([input]);
}
);

it('chunks in to equal pieces', () => {
const result = chunked([1, 2, 3, 4], 2);

expect(result).toEqual([
[1, 2],
[3, 4],
]);
});

it('chunks in to uneven pieces', () => {
const result = chunked([1, 2, 3, 4], 3);

expect(result).toEqual([[1, 2, 3], [4]]);
});
});
22 changes: 22 additions & 0 deletions src/arrays/chunked.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export function chunked<Element>(
array: Element[],
chunkSize: number
): Element[][] {
let buffer: Element[] = [];
const chunks: Element[][] = [];
array.forEach((item, index) => {
buffer.push(item);
if (index % chunkSize !== chunkSize - 1) return;

chunks.push(buffer);
buffer = [];
});

if (buffer.length > 0) {
chunks.push(buffer);
}

return chunks;
}

export default chunked;
1 change: 1 addition & 0 deletions src/arrays/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './compactMap';
export * from './uniques';
export * from './zip';
export * from './chunked';

0 comments on commit 9a0c2af

Please sign in to comment.