Skip to content

Commit 0f0d0b0

Browse files
feat: array chunk algorithm
1 parent a838d26 commit 0f0d0b0

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Option 1
2+
export const chunkArray = (arr: number[], size: number) => {
3+
const chunked = [];
4+
5+
for (const element of arr) {
6+
const last = chunked[chunked.length - 1];
7+
8+
if (!last || last.length === size) {
9+
chunked.push([element]);
10+
} else {
11+
last.push(element);
12+
}
13+
}
14+
15+
return chunked;
16+
};
17+
18+
// Option 2
19+
export const chunkSliced = (arr: number[], size: number) => {
20+
const chunked = [];
21+
let index = 0;
22+
23+
while (index < arr.length) {
24+
chunked.push(arr.slice(index, index + size));
25+
index += size;
26+
}
27+
28+
return chunked;
29+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { describe, test } from 'vitest';
2+
import { chunkArray, chunkSliced } from '../array-chunk';
3+
4+
describe('Array chunk', () => {
5+
test('function chunkArray exists', () => {
6+
expect(typeof chunkArray).toEqual('function');
7+
expect(typeof chunkSliced).toEqual('function');
8+
});
9+
10+
test('chunkArray divides an array of 10 elements with chunk size 2', () => {
11+
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
12+
const chunked = chunkArray(arr, 2);
13+
const sliced = chunkSliced(arr, 2);
14+
15+
expect(chunked).toEqual([
16+
[1, 2],
17+
[3, 4],
18+
[5, 6],
19+
[7, 8],
20+
[9, 10],
21+
]);
22+
expect(sliced).toEqual([
23+
[1, 2],
24+
[3, 4],
25+
[5, 6],
26+
[7, 8],
27+
[9, 10],
28+
]);
29+
});
30+
31+
test('chunkArray divides an array of 3 elements with chunk size 1', () => {
32+
const arr = [1, 2, 3];
33+
const chunked = chunkArray(arr, 1);
34+
const sliced = chunkSliced(arr, 1);
35+
36+
expect(chunked).toEqual([[1], [2], [3]]);
37+
expect(sliced).toEqual([[1], [2], [3]]);
38+
});
39+
40+
test('chunkArray divides an array of 5 elements with chunk size 3', () => {
41+
const arr = [1, 2, 3, 4, 5];
42+
const chunked = chunkArray(arr, 3);
43+
const sliced = chunkSliced(arr, 3);
44+
45+
expect(chunked).toEqual([
46+
[1, 2, 3],
47+
[4, 5],
48+
]);
49+
expect(sliced).toEqual([
50+
[1, 2, 3],
51+
[4, 5],
52+
]);
53+
});
54+
55+
test('chunkArray divides an array of 13 elements with chunk size 5', () => {
56+
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
57+
const chunked = chunkArray(arr, 5);
58+
const sliced = chunkSliced(arr, 5);
59+
60+
expect(chunked).toEqual([
61+
[1, 2, 3, 4, 5],
62+
[6, 7, 8, 9, 10],
63+
[11, 12, 13],
64+
]);
65+
expect(sliced).toEqual([
66+
[1, 2, 3, 4, 5],
67+
[6, 7, 8, 9, 10],
68+
[11, 12, 13],
69+
]);
70+
});
71+
});

0 commit comments

Comments
 (0)