-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplitUp.js
34 lines (27 loc) · 895 Bytes
/
splitUp.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
/**
* Split a given array "array" into "n" chunks.
*
* @param {Array} array
* @param {Number} n
* @return {Array}
*/
module.exports = function splitUp(array, n) {
var rest = array.length % n, // how much to divide
restUsed = rest, // to keep track of the division over the elements
partLength = Math.floor(array.length / n),
result = [];
for(var i = 0; i < array.length; i += partLength) {
var end = partLength + i,
add = false;
if(rest !== 0 && restUsed) { // should add one element for the division
end++;
restUsed--; // we've used one division element now
add = true;
}
result.push(array.slice(i, end)); // part of the array
if(add) {
i++; // also increment i in the case we added an extra element for division
}
}
return result;
}