-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition.ts
More file actions
32 lines (25 loc) · 778 Bytes
/
Copy pathpartition.ts
File metadata and controls
32 lines (25 loc) · 778 Bytes
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
import type { PrototypeStruct } from '../index.js';
type PartitionPredicate<T> = (n: T) => boolean;
interface Partition<T> {
partition(n: PartitionPredicate<T>): [T[], T[]];
}
export const partition: PrototypeStruct = {
label: 'partition',
fn: function arrayPartition<T>(predicate: PartitionPredicate<T>): [T[], T[]] {
const ctx = this as unknown as T[];
const len = ctx.length;
if ('function' !== typeof(predicate)) {
throw new TypeError(`Expect 'predicate' to be a function`);
}
if (!len) return [[], []];
const matched = [];
const rest = [];
for (const n of ctx) {
predicate(n) ? matched.push(n) : rest.push(n);
}
return [matched, rest];
},
};
declare global {
interface Array<T> extends Partition<T> {}
}