simple-statistics
Version:
46 lines (41 loc) • 1.67 kB
JavaScript
/**
* Split an array into chunks of a specified size. This function
* has the same behavior as [PHP's array_chunk](http://php.net/manual/en/function.array-chunk.php)
* function, and thus will insert smaller-sized chunks at the end if
* the input size is not divisible by the chunk size.
*
* `x` is expected to be an array, and `chunkSize` a number.
* The `x` array can contain any kind of data.
*
* @param {Array} x a sample
* @param {number} chunkSize size of each output array. must be a positive integer
* @returns {Array<Array>} a chunked array
* @throws {Error} if chunk size is less than 1 or not an integer
* @example
* chunk([1, 2, 3, 4, 5, 6], 2);
* // => [[1, 2], [3, 4], [5, 6]]
*/
function chunk(x, chunkSize) {
// a list of result chunks, as arrays in an array
const output = [];
// `chunkSize` must be zero or higher - otherwise the loop below,
// in which we call `start += chunkSize`, will loop infinitely.
// So, we'll detect and throw in that case to indicate
// invalid input.
if (chunkSize < 1) {
throw new Error("chunk size must be a positive number");
}
if (Math.floor(chunkSize) !== chunkSize) {
throw new Error("chunk size must be an integer");
}
// `start` is the index at which `.slice` will start selecting
// new array elements
for (let start = 0; start < x.length; start += chunkSize) {
// for each chunk, slice that part of the array and add it
// to the output. The `.slice` function does not change
// the original array.
output.push(x.slice(start, start + chunkSize));
}
return output;
}
export default chunk;