Created
May 27, 2022 11:50
-
-
Save seriousme/d3336dc5e1de19bab3d1f49492ffb71c to your computer and use it in GitHub Desktop.
This file contains 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 { | |
#queue = []; | |
#maxQueueLength = Infinity; | |
#nextResolve = () => {}; | |
#hasNext = false; | |
constructor(maxQueueLength) { | |
if (maxQueueLength) { | |
this.#maxQueueLength = maxQueueLength; | |
} | |
} | |
async *[Symbol.asyncIterator]() { | |
while (true) { | |
yield new Promise((resolve) => { | |
if (this.#queue.length > 0) { | |
return resolve(this.#queue.shift()); | |
} | |
this.#nextResolve = resolve; | |
this.#hasNext = true; | |
}); | |
} | |
} | |
push(item) { | |
if (this.#hasNext) { | |
this.#nextResolve(item); | |
this.#hasNext = false; | |
return; | |
} | |
if (this.#queue.length > this.#maxQueueLength) { | |
this.#queue.shift(); | |
} | |
this.#queue.push(item); | |
} | |
} | |
(async function () { | |
const queue = new AsyncQueue(); | |
setInterval(() => { | |
queue.push(Date.now().toString()); | |
queue.push(Date.now().toString() + "++"); | |
}, 1000); | |
for await (const evt of queue) { | |
console.log(evt); | |
} | |
})(); |
This file contains 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> { | |
private queue: T[] = []; | |
private maxQueueLength = Infinity; | |
private nextResolve = (value: T) => {}; | |
private hasNext = false; | |
constructor(maxQueueLength?: number) { | |
if (maxQueueLength) { | |
this.maxQueueLength = maxQueueLength; | |
} | |
} | |
async *[Symbol.asyncIterator]() { | |
while (true) { | |
yield new Promise((resolve) => { | |
if (this.queue.length > 0) { | |
return resolve(this.queue.shift()); | |
} | |
this.nextResolve = resolve; | |
this.hasNext = true; | |
}); | |
} | |
} | |
push(item: T) { | |
if (this.hasNext) { | |
this.nextResolve(item); | |
this.hasNext = false; | |
return; | |
} | |
if (this.queue.length > this.maxQueueLength) { | |
this.queue.shift(); | |
} | |
this.queue.push(item); | |
} | |
} | |
(async function () { | |
const queue = new AsyncQueue<string>(); | |
setInterval(() => { | |
queue.push(Date.now().toString()); | |
queue.push(Date.now().toString() + "++"); | |
}, 1000); | |
for await (const evt of queue) { | |
console.log(evt); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment