-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplit.ts
53 lines (38 loc) · 1.11 KB
/
split.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import type { PrototypeStruct } from '../index.js';
type SplitPredicate<T> = (x: T) => boolean;
interface Split<T> {
split(predicate: SplitPredicate<T>): T[][];
}
export const split: PrototypeStruct = {
label: 'split',
fn: function arraySplit<T>(predicate: SplitPredicate<T>): T[][] {
const ctx = this as unknown as T[];
if ('function' !== typeof(predicate)) {
throw new TypeError(`Expect 'predicate' to be a function`);
}
const len = ctx.length;
if (!len) return [[]];
const set = [];
let subset = [];
let count = 2;
for (let i = 0; i < len; i += 1) {
const val = ctx[i];
const shouldSplit = predicate(val);
if (shouldSplit) {
count -= 1;
if (subset.length > 0) { set.push(subset); subset = []; }
if (!i) set.push([]);
if (len - 1 === i) set.push([]);
if (!count) { set.push([]); count = 2; }
continue;
}
if (count < 2) count = 2;
subset.push(val);
}
if (subset.length > 0) set.push(subset);
return set;
},
};
declare global {
interface Array<T> extends Split<T> {}
}