UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

69 lines 2.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withLatestFrom = void 0; const Symbol_1 = require("@johngw/stream-common/Symbol"); const ControllableSource_1 = require("@johngw/stream/sources/ControllableSource"); const SourceComposite_1 = require("@johngw/stream/sources/SourceComposite"); /** * Combines the source Observable with other Observables to create an Observable * whose values are calculated from the latest values of each, only when the source emits. * * @group Transformers * @example * ``` * --a-----b-------c---d---e-- * * withLatestFrom( * -----1----2-3-4------------ * ) * * --------b1------c4--d4--e4- * ``` */ function withLatestFrom(...inputs) { const abortController = new AbortController(); const isFilled = (arr) => arr.every((value) => value !== Symbol_1.empty); const inputValues = inputs.map(() => Symbol_1.empty); inputs.forEach((input, index) => input .pipeTo(new WritableStream({ abort(reason) { abortController.abort(reason); }, write(chunk) { inputValues[index] = chunk; }, }), { signal: abortController.signal }) .catch(() => { // errors are handled in the stream object })); const controller = new ControllableSource_1.ControllableSource(); const readable = new ReadableStream(new SourceComposite_1.SourceComposite([ controller, { start, cancel(reason) { abortController.abort(reason); }, }, ])); const writable = new WritableStream({ start, write(chunk) { if (isFilled(inputValues)) controller.enqueue([chunk, ...inputValues]); }, abort(reason) { abortController.abort(reason); }, close() { controller.close(); }, }); return { readable, writable }; function start(controller) { const onAbort = () => controller.error(abortController.signal.reason); abortController.signal.addEventListener('abort', onAbort); } } exports.withLatestFrom = withLatestFrom; //# sourceMappingURL=withLatestFrom.js.map