Created
May 4, 2023 20:02
-
-
Save vezaynk/101cfd0da5f975a91e991e82e12fa2f0 to your computer and use it in GitHub Desktop.
AsyncQueue.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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