UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

53 lines 1.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.roundRobin = void 0; const Array_1 = require("@johngw/stream-common/Array"); const Async_1 = require("@johngw/stream-common/Async"); const Stream_1 = require("@johngw/stream-common/Stream"); const fromCollection_1 = require("@johngw/stream/sources/fromCollection"); const SourceComposite_1 = require("@johngw/stream/sources/SourceComposite"); /** * Given an ordered list of streams, queue their items from one stream at a time. * * @group Sources * @see {@link merge:function} * @example * ``` * roundRobin([ * --1------2------3------4------- * ----one-two--three------------- * ]) * * --1-one--2-two--3-three-4------ * ``` */ function roundRobin(streams, queuingStrategy) { let readers = streams.map((stream) => stream.getReader()); return !streams.length ? (0, Stream_1.immediatelyClosingReadableStream)() : new ReadableStream(new SourceComposite_1.SourceComposite([ new fromCollection_1.IteratorSource(generateReadResults()), { async cancel(reason) { await (0, Async_1.all)(readers, (reader) => reader.cancel(reason)); }, }, ]), queuingStrategy); async function* generateReadResults() { let index = 0; while (readers.length) { if (!(index in readers)) index = 0; const reader = readers[index]; const result = await reader.read(); if (result.done) readers = (0, Array_1.without)(readers, reader); else { yield result.value; index++; } } } } exports.roundRobin = roundRobin; //# sourceMappingURL=roundRobin.js.map