UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

34 lines 921 B
import { pipeFlushes } from '@johngw/stream-common/Stream'; /** * Reduces chunks in to one accumulator. Once the stream is cancelled, * the accumulator will be queued. * * @group Transformers * @see {@link accumulate:function} * @example * * --a-------b-------c-----| * * reduce([], (acc, chunk) => [...acc, chunk]) * * ------------------------[a,b,c]-| */ export function reduce(acc, fn, options) { return new TransformStream({ start(controller) { pipeFlushes(() => controller.enqueue(acc), (error) => controller.error(error), options); }, async transform(chunk, controller) { try { acc = await fn(acc, chunk); } catch (error) { controller.error(error); } }, flush(controller) { controller.enqueue(acc); }, }); } //# sourceMappingURL=reduce.js.map