-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathzip.ts
More file actions
41 lines (38 loc) · 1.15 KB
/
zip.ts
File metadata and controls
41 lines (38 loc) · 1.15 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
export function* zip<T extends Array<unknown>>(
...iterables: { [K in keyof T]: Iterable<T[K]> }
): Iterable<{ [K in keyof T]: T[K] | undefined }> {
const iterators = iterables.map((iterable) => iterable[Symbol.iterator]());
while (true) {
const values = [];
let hasMore = false;
for (const iterator of iterators) {
const { done, value } = iterator.next();
hasMore ||= !done;
values.push(value);
}
if (!hasMore) {
return;
}
yield values as T;
}
}
export async function* zipAsync<T extends Array<unknown>>(
...iterables: { [K in keyof T]: AsyncIterable<T[K]> }
): AsyncIterable<{ [K in keyof T]: T[K] | undefined }> {
const iterators = iterables.map((iterable) =>
iterable[Symbol.asyncIterator]()
);
while (true) {
const values = [];
let hasMore = false;
for (const iterator of iterators) {
const { done, value } = await iterator.next();
hasMore ||= !done;
values.push(value);
}
if (!hasMore) {
return;
}
yield values as T;
}
}