-
Notifications
You must be signed in to change notification settings - Fork 1
/
segregate.js
46 lines (36 loc) · 989 Bytes
/
segregate.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
46
function sum(x, y) {
return x + y;
}
// This will do the calc for determining the actual number of groups
function getGroups(groups, items) {
var length = items.length;
if (!groups.length) {
return [length];
}
var total = groups.reduce(sum, 0);
if (length > total) {
return groups.concat(length - total);
}
return groups;
}
// This does an uneven split of any generic item array into groups.
function segregate(groups, items) {
var initialValue = {nextIndex: 0, groups: []};
var distribution = getGroups(groups, items);
return distribution.reduce(function(acc, count) {
var nextIndex = acc.nextIndex;
var groups = acc.groups;
var end = nextIndex + count;
if (nextIndex > items.length) {
return {
nextIndex: nextIndex,
groups: groups
};
}
return {
nextIndex: end,
groups: groups.concat([items.slice(nextIndex, end)])
};
}, initialValue).groups;
}
module.exports = segregate;