UNPKG

2.27 kBJavaScriptView Raw
1export const isIterable = (x) => x != null && typeof x === 'object' && Symbol.iterator in x;
2export const isAsyncIterable = (x) => x != null && typeof x === 'object' && Symbol.asyncIterator in x;
3export const isForAwaitable = (x) => x != null && typeof x === 'object' && (Symbol.asyncIterator in x || Symbol.iterator in x);
4/**
5 * Alternates items from the first and second iterable in the output iterable, until either input runs out of items.
6 */
7export function* interleave(xs, ys) {
8 const itx = xs[Symbol.iterator]();
9 const ity = ys[Symbol.iterator]();
10 while (true) {
11 const rx = itx.next();
12 if (rx.done)
13 break;
14 else
15 yield rx.value;
16 const ry = ity.next();
17 if (ry.done)
18 break;
19 else
20 yield ry.value;
21 }
22}
23/**
24 * It's like interleave, but will flatten items of the second (async) iterable.
25 */
26export async function* aInterleaveFlattenSecond(xs, ys) {
27 const itx = xs[Symbol.iterator]();
28 const ity = ys[Symbol.iterator]();
29 while (true) {
30 const rx = itx.next();
31 if (rx.done)
32 break;
33 else
34 yield rx.value;
35 const ry = ity.next();
36 if (ry.done)
37 break;
38 else
39 yield* ry.value;
40 }
41}
42export function* map(iterable, f) {
43 for (const x of iterable)
44 yield f(x);
45}
46export async function* aMap(iterable, f) {
47 for await (const x of iterable)
48 yield f(x);
49}
50export function join(iterable) {
51 return [...iterable].join('');
52}
53export async function aJoin(iterable) {
54 const chunks = [];
55 for await (const x of iterable)
56 chunks.push(x);
57 return chunks.join('');
58}
59export async function collect(iterable) {
60 const chunks = [];
61 for await (const x of iterable)
62 chunks.push(x);
63 return chunks;
64}
65export async function* promiseToAsyncIter(promise) {
66 yield await promise;
67}
68export function promiseToStream(promise) {
69 return new ReadableStream({
70 async start(ctrl) {
71 try {
72 ctrl.enqueue(await promise);
73 ctrl.close();
74 }
75 catch (err) {
76 ctrl.error(err);
77 }
78 }
79 });
80}
81//# sourceMappingURL=iter.js.map
\No newline at end of file