UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

56 lines 1.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ForkableReplaySink = void 0; const ForkableSink_1 = require("@johngw/stream/sinks/ForkableSink"); /** * An extension to the {@link ForkableSink:class} that immediately * queues the entire contents of whatever has been previously consumed. * * @group Sinks * @see {@link ForkableReplayStream:class} * @example * ``` * const forkable = new ForkableReplayStream<number>() * const writable = new WritableStream(forkable) * await fromCollection([1, 2, 3, 4, 5, 6, 7]).pipeTo(writable) * ``` * * Now the stream has finished, if we fork from it we'll * receive the entire events that were published to it. * * ``` * await forkable.fork().pipeTo(write(console.info)) * // 1 * // 2 * // 3 * // 4 * // 5 * // 6 * // 7 * ``` */ class ForkableReplaySink extends ForkableSink_1.ForkableSink { #chunks = []; #maxReplaySize = Number.MAX_SAFE_INTEGER; constructor(maxReplaySize = Number.MAX_SAFE_INTEGER) { super(); this.#maxReplaySize = maxReplaySize; } write(chunk) { if (this.#chunks.length === this.#maxReplaySize) this.#chunks.shift(); this.#chunks.push(chunk); return super.write(chunk); } _addController(underlyingSource, queuingStrategy) { const [controller, stream] = super._addController(underlyingSource, queuingStrategy); for (const chunk of this.#chunks) controller.enqueue(chunk); return [controller, stream]; } clear() { this.#chunks = []; } } exports.ForkableReplaySink = ForkableReplaySink; //# sourceMappingURL=ForkableReplaySink.js.map