UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

52 lines 1.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buffer = void 0; const Stream_1 = require("@johngw/stream-common/Stream"); /** * Buffers the source stream chunks until `notifier` emits. * * @group Transformers * @example * ``` * --a--b--c--d--e--f--g--h--i--| * * buffer( * --------B--------B--------B--| * ) * * --------[a,b,c]--[d,e,f]--[g,h,i]-| * ``` */ function buffer(notifier, maxBuffer = Number.MAX_SAFE_INTEGER) { const abortController = new AbortController(); let buffer = []; return new TransformStream({ start(controller) { notifier .pipeTo((0, Stream_1.write)(() => { if (buffer.length) { controller.enqueue(buffer); buffer = []; } }), { signal: abortController.signal }) .then(() => // Typescript still thinks that `flush` may not be set. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.flush(controller)) .catch((error) => controller.error(error)); }, transform(chunk) { if (buffer.length === maxBuffer) buffer.shift(); buffer.push(chunk); }, flush(controller) { if (buffer.length) controller.enqueue(buffer); controller.terminate(); abortController.abort(); }, }); } exports.buffer = buffer; //# sourceMappingURL=buffer.js.map