-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
zip.ts
53 lines (52 loc) · 1.69 KB
/
zip.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
/**
* Zips multiple iterables into a single iterable.
*
* The resulting iterable will yield arrays of elements from the input iterables.
* The first array will contain the first element of each input iterable, the second array will contain the second element of each input iterable, and so on.
*
* If the input iterables have different lengths, the resulting iterable will stop when the shortest input iterable is exhausted.
* The remaining elements from the longer input iterables will be ignored.
*
* Use {@linkcode https://jsr.io/@core/iterutil/doc/chain/~/chain chain} to chain iterables.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/enumerate/~/enumerate enumerate} to zip with indices.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/async/zip/~/async zip async zip} to zip asynchronously.;w
*
* @param iterables The iterables to zip.
* @returns The zipped iterable.
*
* @example
* ```ts
* import { zip } from "@core/iterutil/zip";
*
* const iter = zip(
* [1, 2, 3],
* ["a", "b", "c"],
* [true, false, true],
* );
* console.log(Array.from(iter)); // [[1, "a", true], [2, "b", false], [3, "c", true]]
* ```
*/
export function* zip<
U extends readonly [
Iterable<unknown>,
Iterable<unknown>,
...Iterable<unknown>[],
],
>(
...iterables: U
): Iterable<Zip<U>> {
const iterators = iterables.map((it) => it[Symbol.iterator]());
while (true) {
const results = iterators.map((it) => it.next());
if (results.find(({ done }) => !!done)) {
break;
}
yield results.map(({ value }) => value) as Zip<U>;
}
}
/**
* @internal
*/
export type Zip<T extends readonly Iterable<unknown>[]> = {
[P in keyof T]: T[P] extends Iterable<infer U> ? U : never;
};