Skip to content

Instantly share code, notes, and snippets.

@AKST
Created November 29, 2025 09:31
Show Gist options
  • Select an option

  • Save AKST/bd9903dd4a6488eb1ccf8333eb8d84fa to your computer and use it in GitHub Desktop.

Select an option

Save AKST/bd9903dd4a6488eb1ccf8333eb8d84fa to your computer and use it in GitHub Desktop.
export class Queue {
#buffer = [];
#p = Promise.withResolvers();
#stopped = false;
push(value) {
if (this.#stopped) throw new Error('Queue is stopped');
this.#buffer.push(value);
this.#p.resolve();
}
stop() {
this.#stopped = true;
this.#p.resolve();
}
async *read() {
while (true) {
while (this.#buffer.length > 0) yield this.#buffer.shift();
if (this.#stopped) return;
await this.#p.promise;
this.#p = Promise.withResolvers();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment