-
Notifications
You must be signed in to change notification settings - Fork 7
/
groupWith.ts
36 lines (30 loc) · 1.05 KB
/
groupWith.ts
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
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import type { PH, Predicate2 } from './utils/types.ts';
import curryN from './utils/curry_n.ts';
import { slice } from './slice.ts';
// @types
type GroupWith_2<L extends T[] | string, T> = (functor: L) => L[];
type GroupWith_1<L extends T[] | string, T> = (predicate: Predicate2<T>) => L[];
type GroupWith =
& (<L extends T[] | string, T>(predicate: Predicate2<T>) => GroupWith_2<L, T>)
& (<L extends T[] | string, T>(
predicate: PH,
functor: L,
) => GroupWith_1<L, T>)
& (<L extends T[] | string, T>(predicate: Predicate2<T>, functor: L) => L[]);
function _groupWith<L extends T[] | string, T>(
predicate: Predicate2<T | string>,
functor: L,
) {
const result: T[][] | string[] = [];
const len = functor.length;
let i = 0;
while (i < len) {
let j = i + 1;
while (j < len && predicate(functor[j - 1], functor[j])) j++;
result.push(slice(i, j, functor) as T[] & string);
i = j;
}
return result;
}
export const groupWith = curryN(2, _groupWith) as GroupWith;