forked from ramda/ramda
/
groupWith.js
48 lines (47 loc) · 1.55 KB
/
groupWith.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
48
import _curry2 from './internal/_curry2.js';
/**
* Takes a list and returns a list of lists where each sublist's elements are
* all satisfied pairwise comparison according to the provided function.
* Only adjacent elements are passed to the comparison function.
*
* @func
* @memberOf R
* @since v0.21.0
* @category List
* @sig ((a, a) → Boolean) → [a] → [[a]]
* @param {Function} fn Function for determining whether two given (adjacent)
* elements should be in the same group
* @param {Array} list The array to group. Also accepts a string, which will be
* treated as a list of characters.
* @return {List} A list that contains sublists of elements,
* whose concatenations are equal to the original list.
* @example
*
* R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21])
* //=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]]
*
* R.groupWith((a, b) => a + 1 === b, [0, 1, 1, 2, 3, 5, 8, 13, 21])
* //=> [[0, 1], [1, 2, 3], [5], [8], [13], [21]]
*
* R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21])
* //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]]
*
* const isVowel = R.test(/^[aeiou]$/i);
* R.groupWith(R.eqBy(isVowel), 'aestiou')
* //=> ['ae', 'st', 'iou']
*/
var groupWith = _curry2(function(fn, list) {
var res = [];
var idx = 0;
var len = list.length;
while (idx < len) {
var nextidx = idx + 1;
while (nextidx < len && fn(list[nextidx - 1], list[nextidx])) {
nextidx += 1;
}
res.push(list.slice(idx, nextidx));
idx = nextidx;
}
return res;
});
export default groupWith;