Skip to content

Commit

Permalink
feat: array chunk algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
francislagares committed Aug 16, 2023
1 parent a838d26 commit 0f0d0b0
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/algorithms/array-chunk/array-chunk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Option 1
export const chunkArray = (arr: number[], size: number) => {
const chunked = [];

for (const element of arr) {
const last = chunked[chunked.length - 1];

if (!last || last.length === size) {
chunked.push([element]);
} else {
last.push(element);
}
}

return chunked;
};

// Option 2
export const chunkSliced = (arr: number[], size: number) => {
const chunked = [];
let index = 0;

while (index < arr.length) {
chunked.push(arr.slice(index, index + size));
index += size;
}

return chunked;
};
71 changes: 71 additions & 0 deletions src/algorithms/array-chunk/tests/array-chunk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { describe, test } from 'vitest';
import { chunkArray, chunkSliced } from '../array-chunk';

describe('Array chunk', () => {
test('function chunkArray exists', () => {
expect(typeof chunkArray).toEqual('function');
expect(typeof chunkSliced).toEqual('function');
});

test('chunkArray divides an array of 10 elements with chunk size 2', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunked = chunkArray(arr, 2);
const sliced = chunkSliced(arr, 2);

expect(chunked).toEqual([
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
]);
expect(sliced).toEqual([
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
]);
});

test('chunkArray divides an array of 3 elements with chunk size 1', () => {
const arr = [1, 2, 3];
const chunked = chunkArray(arr, 1);
const sliced = chunkSliced(arr, 1);

expect(chunked).toEqual([[1], [2], [3]]);
expect(sliced).toEqual([[1], [2], [3]]);
});

test('chunkArray divides an array of 5 elements with chunk size 3', () => {
const arr = [1, 2, 3, 4, 5];
const chunked = chunkArray(arr, 3);
const sliced = chunkSliced(arr, 3);

expect(chunked).toEqual([
[1, 2, 3],
[4, 5],
]);
expect(sliced).toEqual([
[1, 2, 3],
[4, 5],
]);
});

test('chunkArray divides an array of 13 elements with chunk size 5', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const chunked = chunkArray(arr, 5);
const sliced = chunkSliced(arr, 5);

expect(chunked).toEqual([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13],
]);
expect(sliced).toEqual([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13],
]);
});
});

0 comments on commit 0f0d0b0

Please sign in to comment.