Skip to content

Instantly share code, notes, and snippets.

@seriousme
Created May 27, 2022 11:50
Show Gist options
  • Save seriousme/d3336dc5e1de19bab3d1f49492ffb71c to your computer and use it in GitHub Desktop.
Save seriousme/d3336dc5e1de19bab3d1f49492ffb71c to your computer and use it in GitHub Desktop.
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);
}
})();
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