UNPKG

evnty

Version:

Async-first, reactive event handling library for complex event flows in browser and Node.js

59 lines (57 loc) 1.6 kB
import { Async } from "./async.js"; import { Signal } from "./signal.js"; import { RingBuffer } from "./ring-buffer.js"; export class Sequence extends Async { #queue; #nextSignal; #sendSignal; [Symbol.toStringTag] = 'Sequence'; static merge(target, ...sequences) { for (const source of sequences){ queueMicrotask(async ()=>{ if (!target.disposed) try { const sink = target.sink; for await (const value of source){ if (!sink(value)) { return; } } } catch {} }); } } constructor(abortSignal){ super(abortSignal); this.#queue = new RingBuffer(); this.#nextSignal = new Signal(abortSignal); this.#sendSignal = new Signal(abortSignal); } get size() { return this.#queue.length; } async reserve(capacity) { while(this.#queue.length > capacity){ await this.#sendSignal; } } emit(value) { const ok = !this.disposed; if (ok) { this.#queue.push(value); } this.#nextSignal.emit(); return ok; } async receive() { while(!this.#queue.length){ await this.#nextSignal; } this.#sendSignal.emit(); return this.#queue.shift(); } dispose() { this.#sendSignal[Symbol.dispose](); this.#nextSignal[Symbol.dispose](); } } //# sourceMappingURL=sequence.js.map