UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

63 lines 1.94 kB
import { empty } from '@johngw/stream-common/Symbol'; import { ControllableSource } from '../sources/ControllableSource.js'; import { SourceComposite } from '../sources/SourceComposite.js'; /** * 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- * ``` */ export function withLatestFrom(...inputs) { const abortController = new AbortController(); const isFilled = (arr) => arr.every((value) => value !== empty); const inputValues = inputs.map(() => empty); inputs.forEach((input, index) => input .pipeTo(new WritableStream({ abort(reason) { abortController.abort(reason); }, write(chunk) { inputValues[index] = chunk; }, }), { signal: abortController.signal }) .catch(() => { })); const controller = new ControllableSource(); const readable = new ReadableStream(new 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); } } //# sourceMappingURL=withLatestFrom.js.map