Skip to content

Instantly share code, notes, and snippets.

@stuartambient
Created January 11, 2021 01:01
Show Gist options
  • Save stuartambient/ab33f27380381709cf9a67a31fa32d97 to your computer and use it in GitHub Desktop.
Save stuartambient/ab33f27380381709cf9a67a31fa32d97 to your computer and use it in GitHub Desktop.
NodeJS Design Patters (third edition) challenges
class TaskQueue {
constructor(concurrency) {
this.taskQueue = [];
this.consumerQueue = [];
for (let i = 0; i < concurrency; i++) {
this.consumer();
}
}
consumer() {
return new Promise((resolve, reject) => {
const task = this.getNextTask();
resolve(task);
})
.then(task => task())
.then(res => console.log(res))
.then(() => {
if (this.taskQueue.length !== 0) this.consumer();
});
}
getNextTask() {
return new Promise(resolve => {
if (this.taskQueue.length !== 0) {
return resolve(this.taskQueue.shift());
}
this.consumerQueue.push(resolve);
});
}
runTask(task) {
return new Promise((resolve, reject) => {
const taskWrapper = () => {
const taskPromise = task();
taskPromise.then(resolve, reject);
return taskPromise;
};
if (this.consumerQueue.length !== 0) {
const consumer = this.consumerQueue.shift();
consumer(taskWrapper);
} else {
this.taskQueue.push(taskWrapper);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment