forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterables.ts
More file actions
53 lines (45 loc) · 1.11 KB
/
iterables.ts
File metadata and controls
53 lines (45 loc) · 1.11 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
export function* joinIterables<T>(...iters: Iterable<T>[]) {
for (const iter of iters) {
yield* iter;
}
}
function* filterIter<T>(
iter: Iterable<T>,
p: (t: T, index: number) => boolean,
): Iterable<T> {
let index = 0;
for (const t of iter) {
if (p(t, index++)) {
yield t;
}
}
}
function* mapIter<T, U>(
iter: Iterable<T>,
f: (t: T, index: number) => U,
): Iterable<U> {
let index = 0;
for (const t of iter) {
yield f(t, index++);
}
}
// TODO(arv): Use ES2024 Iterable.from when available
// https://github.com/tc39/proposal-iterator-helpers
class IterWrapper<T> implements Iterable<T> {
iter: Iterable<T>;
constructor(iter: Iterable<T>) {
this.iter = iter;
}
[Symbol.iterator]() {
return this.iter[Symbol.iterator]();
}
map<U>(f: (t: T, index: number) => U): IterWrapper<U> {
return new IterWrapper(mapIter(this.iter, f));
}
filter(p: (t: T, index: number) => boolean): IterWrapper<T> {
return new IterWrapper(filterIter(this.iter, p));
}
}
export function wrapIterable<T>(iter: Iterable<T>): IterWrapper<T> {
return new IterWrapper(iter);
}