-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
47 lines (40 loc) · 802 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
42
43
44
45
46
47
/**
* Group list of objects given a sorting callback.
*
* @param {Array} arr
* @param {Function} cb
* @api public
*/
module.exports = (arr, cb) => {
let list = [...arr]
const result = []
while (list.length) {
const {alike, remaining} = group(list, cb)
result.push(alike)
list = remaining
}
return result
}
/**
* Traverse list of objects and return group
* of object as well as remaining objects.
*
* @param {Array} list
* @param {Function} cb
* @return {Object}
* @api private
*/
function group (list, cb) {
const alike = []
const remaining = []
const a = list.shift()
list.map(b => {
const bool = cb(a, b)
if (bool) alike.push(b)
else remaining.push(b)
})
return {
alike: alike.length > 0 ? [a, ...alike] : a,
remaining
}
}