mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 02:44:45 +00:00
feat(packages/stdlib): add cluster arrays util
This commit is contained in:
34
packages/stdlib/src/arrays/cluster/index.test.ts
Normal file
34
packages/stdlib/src/arrays/cluster/index.test.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { cluster } from '.';
|
||||
|
||||
describe('cluster', () => {
|
||||
it('cluster an array into subarrays of a specific size', () => {
|
||||
const result = cluster([1, 2, 3, 4, 5, 6, 7, 8], 3);
|
||||
expect(result).toEqual([[1, 2, 3], [4, 5, 6], [7, 8]]);
|
||||
});
|
||||
|
||||
it('handle arrays that are not perfectly divisible by the size', () => {
|
||||
const result = cluster([1, 2, 3, 4, 5], 2);
|
||||
expect(result).toEqual([[1, 2], [3, 4], [5]]);
|
||||
});
|
||||
|
||||
it('return an array with each element in its own subarray if size is 1', () => {
|
||||
const result = cluster([1, 2, 3, 4], 1);
|
||||
expect(result).toEqual([[1], [2], [3], [4]]);
|
||||
});
|
||||
|
||||
it('return an array with a single subarray if size is greater than the array length', () => {
|
||||
const result = cluster([1, 2, 3], 5);
|
||||
expect(result).toEqual([[1, 2, 3]]);
|
||||
});
|
||||
|
||||
it('return an empty array if size is less than or equal to 0', () => {
|
||||
const result = cluster([1, 2, 3, 4], -1);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('return an empty array if the input array is empty', () => {
|
||||
const result = cluster([], 3);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
24
packages/stdlib/src/arrays/cluster/index.ts
Normal file
24
packages/stdlib/src/arrays/cluster/index.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* @name cluster
|
||||
* @category Arrays
|
||||
* @description Cluster an array into subarrays of a specific size
|
||||
*
|
||||
* @param {Value[]} arr The array to cluster
|
||||
* @param {number} size The size of each cluster
|
||||
* @returns {Value[][]} The clustered array
|
||||
*
|
||||
* @example
|
||||
* cluster([1, 2, 3, 4, 5, 6, 7, 8], 3) // => [[1, 2, 3], [4, 5, 6], [7, 8]]
|
||||
*
|
||||
* @example
|
||||
* cluster([1, 2, 3, 4], -1) // => []
|
||||
*
|
||||
* @since 0.0.3
|
||||
*/
|
||||
export function cluster<Value>(arr: Value[], size: number): Value[][] {
|
||||
if (size <= 0) return [];
|
||||
|
||||
const clusterLength = Math.ceil(arr.length / size);
|
||||
|
||||
return Array.from({ length: clusterLength }, (_, i) => arr.slice(i * size, i * size + size));
|
||||
}
|
||||
Reference in New Issue
Block a user