implemented a basic Asynchronous Queue so, that I can do
await queue.push(item);
const item = await queue.pop();
basically I'm trying to convert a synchronous queue implementation into asynchronous one by using listeners for every pop operation if the queue is empty.
class Queue {
constructor() {
this.dict = {};
this.start = 0;
this.end = 0;
}
/**
*
* todo: if the number of operations exceed Number.MAX_SAFE_INTEGER (~ 2**53)
* todo: there will be overflow errors, so shift the elements
* todo: and make the operations asymptotically O(1)
*
* @param {*} item
*/
push (item) {
this.dict[this.end] = item;
this.end += 1;
}
get length() {
return this.end - this.start;
}
/**
*
* @returns {*}
*/
pop () {
if (this.start === this.end) {
throw "OutOfBounds Exception, can't pop from an empty queue";
}
const item = this.dict[this.start];
this.start += 1;
return item;
}
}
class AsyncQueue {
constructor() {
this.sync_queue = new Queue();
this.waiting_minions = new Queue();
}
async push(item) {
if (this.waiting_minions.length > 0) {
const signal = this.waiting_minions.pop();
await signal(item);
} else {
this.sync_queue.push(item);
}
}
get length() {
return this.sync_queue.length;
}
pop() {
return new Promise((resolve) => {
if (this.sync_queue.length > 0) {
return resolve(this.sync_queue.pop());
}
this.waiting_minions.push(resolve);
});
}
}
module.exports = AsyncQueue;