-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition.ts
More file actions
55 lines (49 loc) · 1.67 KB
/
partition.ts
File metadata and controls
55 lines (49 loc) · 1.67 KB
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
54
55
import type { IterFn, Prettify } from "./_types";
type PartitionResult<T, F = T> = [passed: T[], failed: F[]];
/**
* Splits an iterable into two arrays based on a predicate function.
* @example
* ```ts
* partition([1,2,3,4], x => x % 2 === 0) // [[2, 4], [1, 3]]
* partition(x => x > 2)([1,2,3,4]) // [[3, 4], [1, 2]]
* ```
*/
export function partition<T, U extends T = T>(
predicate: (item: T, index: number) => item is U
): (iter: Iterable<T>) => Prettify<PartitionResult<U, Exclude<T, U>>>;
export function partition<T>(
predicate: IterFn<T>
): (iter: Iterable<T>) => Prettify<PartitionResult<T>>;
export function partition<T, U extends T = T>(
iter: Iterable<T>,
predicate: (item: T, index: number) => item is U
): Prettify<PartitionResult<U, Exclude<T, U>>>;
export function partition<T>(
iter: Iterable<T>,
predicate: IterFn<T>
): Prettify<PartitionResult<T>>;
export function partition<T>(
predicateOrIter: IterFn<T> | Iterable<T>,
maybePredicate?: IterFn<T>
): PartitionResult<T> | ((iter: Iterable<T>) => PartitionResult<T>) {
if (typeof predicateOrIter === "function") {
// Curried form: return a function that takes an iterable
return (iter: Iterable<T>) => _partition(iter, predicateOrIter);
}
// Direct form: partition the iterable with the predicate
return _partition(predicateOrIter, maybePredicate!);
}
function _partition<T>(
iter: Iterable<T>,
predicate: IterFn<T>
): PartitionResult<T> {
const passed: T[] = [];
const failed: T[] = [];
const output: [passed: T[], failed: T[]] = [passed, failed];
let i = 0;
for (const item of iter) {
if (predicate(item, i++)) passed.push(item);
else failed.push(item);
}
return output;
}