UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

38 lines 1.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reduce = void 0; const Stream_1 = require("@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]-| */ function reduce(acc, fn, options) { return new TransformStream({ start(controller) { (0, Stream_1.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); }, }); } exports.reduce = reduce; //# sourceMappingURL=reduce.js.map