import EventSet from "@entity-access/entity-access/dist/common/EventSet.js"; export default class Queue { public readonly eventItemAdded: EventSet = new EventSet(this); get peek() { return this.store.get(this.head); } get isEmpty() { return this.head === this.tail; } get signal() { return this.abortController.signal; } private readonly abortController: AbortController = new AbortController(); private head = 0; private tail = 0; private readonly store: Map = new Map(); private aborted = null; public async waitForPeek(signal?: AbortSignal) { if (this.isEmpty) { await new Promise((resolve, reject)=> { this.eventItemAdded.listenOnce(resolve); signal?.addEventListener("abort", () => { this.abortController.abort("abort"); reject("abort"); }); }); } if (this.aborted) { throw this.aborted; } return this.peek; } public error(e) { this.aborted = e; this.eventItemAdded.dispatch(null); } public enqueue(item: T) { this.aborted = null; this.store.set(this.tail,item); this.tail++; this.eventItemAdded.dispatch(item); } public dequeue() { if (this.aborted) { throw this.aborted; } const { head, tail } = this; const size = tail - head; if (size <= 0) { return void 0; } const item = this.store.get(head); this.store.delete(head); this.head++; if (this.head === this.tail) { this.head = 0; this.tail = 0; } return item; } }