/
zip.ts
37 lines (33 loc) 路 1.23 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
import type { IsomorphicIterable } from "@lou.codes/types";
import { createIterableIterator } from "./createIterableIterator.js";
import { getIterator } from "./getIterator.js";
/**
* Takes two iterables or asynchronous iterable and returns a new iterable or
* asynchronous iterable with the length of the shortest iterable with tuples
* containing the items from both.
*
* @category Asynchronous Generators
* @example
* ```typescript
* const zipNumbers = zip([0, 1, 2]);
* zipNumbers([3, 4, 5]); // [[0, 3], [1, 4], [2, 5]]
* ```
* @param iterableFirst One of the iterables to be zipped.
* @returns Curried function with `iterableFirst` in context.
*/
export const zip =
<ItemFirst>(iterableFirst: IsomorphicIterable<ItemFirst>) =>
<ItemSecond>(iterableSecond: IsomorphicIterable<ItemSecond>) =>
createIterableIterator(async function* () {
const asyncIteratorSecond = getIterator(iterableSecond);
// eslint-disable-next-line functional/no-loop-statements
for await (const itemFirst of iterableFirst) {
const { done = false, value } =
await asyncIteratorSecond.next();
// eslint-disable-next-line functional/no-conditional-statements
if (done) {
break;
}
yield [itemFirst, value] as const;
}
});