mirror of
https://github.com/swc-project/swc.git
synced 2024-12-20 20:22:26 +03:00
52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
|
// Loaded from https://deno.land/x/ramda@v0.27.2/source/groupWith.js
|
||
|
|
||
|
|
||
|
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;
|