-
Notifications
You must be signed in to change notification settings - Fork 224
/
chunk.js
45 lines (41 loc) · 1.63 KB
/
chunk.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 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;