Skip to content

Instantly share code, notes, and snippets.

@vezaynk
Created May 4, 2023 20:02
Show Gist options
  • Save vezaynk/101cfd0da5f975a91e991e82e12fa2f0 to your computer and use it in GitHub Desktop.
Save vezaynk/101cfd0da5f975a91e991e82e12fa2f0 to your computer and use it in GitHub Desktop.
AsyncQueue.ts
class AsyncQueue<T> {
#elements: T[] = [];
#waiting: ((el: T) => void)[] = [];
get size() { return this.#elements.length }
enqueue(el: T) {
const next = this.#waiting.shift();
if (next) {
next(el);
} else {
this.#elements.push(el);
}
}
async dequeue() {
const next = this.#elements.shift();
if (next) {
return next;
} else {
const defer = new Promise<T>(res => this.#waiting.push(res))
return defer;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment