Created
January 11, 2021 01:01
-
-
Save stuartambient/ab33f27380381709cf9a67a31fa32d97 to your computer and use it in GitHub Desktop.
NodeJS Design Patters (third edition) challenges
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 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