UNPKG

@worker-tools/stream-response

Version:

Fetch API Response objects made from async generators. Build streaming HTML responses or SSE with JS sugar.

81 lines 2.27 kB
export const isIterable = (x) => x != null && typeof x === 'object' && Symbol.iterator in x; export const isAsyncIterable = (x) => x != null && typeof x === 'object' && Symbol.asyncIterator in x; export const isForAwaitable = (x) => x != null && typeof x === 'object' && (Symbol.asyncIterator in x || Symbol.iterator in x); /** * Alternates items from the first and second iterable in the output iterable, until either input runs out of items. */ export function* interleave(xs, ys) { const itx = xs[Symbol.iterator](); const ity = ys[Symbol.iterator](); while (true) { const rx = itx.next(); if (rx.done) break; else yield rx.value; const ry = ity.next(); if (ry.done) break; else yield ry.value; } } /** * It's like interleave, but will flatten items of the second (async) iterable. */ export async function* aInterleaveFlattenSecond(xs, ys) { const itx = xs[Symbol.iterator](); const ity = ys[Symbol.iterator](); while (true) { const rx = itx.next(); if (rx.done) break; else yield rx.value; const ry = ity.next(); if (ry.done) break; else yield* ry.value; } } export function* map(iterable, f) { for (const x of iterable) yield f(x); } export async function* aMap(iterable, f) { for await (const x of iterable) yield f(x); } export function join(iterable) { return [...iterable].join(''); } export async function aJoin(iterable) { const chunks = []; for await (const x of iterable) chunks.push(x); return chunks.join(''); } export async function collect(iterable) { const chunks = []; for await (const x of iterable) chunks.push(x); return chunks; } export async function* promiseToAsyncIter(promise) { yield await promise; } export function promiseToStream(promise) { return new ReadableStream({ async start(ctrl) { try { ctrl.enqueue(await promise); ctrl.close(); } catch (err) { ctrl.error(err); } } }); } //# sourceMappingURL=iter.js.map