-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (34 loc) · 957 Bytes
/
index.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
/**
* Group an array of numbers.
*
* The function returns an array with the contents of the 'arr' input
* grouped in a sub array of length 'size'.
*
* The function will throw an error if 'arr' is not an array.
* If 'size' is less than 1 or not a number, an error will also be thrown.
* When length of 'arr' is not exactly divisible by 'size', the last element
* will contain the remainder.
*
* @param array arr
* @param number size
*/
function groupArrayElements(arr, size) {
if (!Array.isArray(arr)) {
throw new Error("Invalid arr argument");
}
if (!Number.isInteger(size)) {
throw new Error("Invalid size argument");
}
if (size < 1) {
throw new Error("Size argument cannot be less than 1");
}
if (arr.length === 0) {
return [];
}
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
module.exports = { groupArrayElements };