Skip to content

Instantly share code, notes, and snippets.

@btn0s
Created January 28, 2022 21:53
Show Gist options
  • Save btn0s/523335c7573aad3a4149c2f14c243a0a to your computer and use it in GitHub Desktop.
Save btn0s/523335c7573aad3a4149c2f14c243a0a to your computer and use it in GitHub Desktop.
/*
Question:
Use the following code to implement a TaskRunner.
A TaskRunner takes a "task" function, and executes it.
The "task" function takes a "done" callback function which will be invoked when the task completes execution.
Users can add more than 1 task functions to the task runner, however, when the number of concurrently executed task functions reaches the "concurrency" threshold, new task functions will be "queued", until any running task functions completes its execution (hint: the "done" callback function of that task will be invoked).
*/
// Constructor of TaskRunner
class TaskRunner {
constructor(concurrency) {
this.taskLimit = concurrency;
this.currentTasks = 0;
this.taskQueue = [];
}
run = (task) => {
// Check limit and conditionally run task or add to taskQueue
if (this.currentTasks === this.taskLimit) {
this.taskQueue.push(task);
console.log('limit hit, task pushed to queue', this.currentTasks, this.taskQueue);
} else {
task(this.done);
this.currentTasks += 1;
console.log('task run immediately', this.currentTasks, this.taskQueue);
}
}
done = () => {
// Callback to signal when a task has completed and needs to be removed from currentTasks
this.currentTasks -= 1;
if (this.taskQueue.length >= 1) {
this.taskQueue[0](this.done);
this.taskQueue.splice(0, 1);
console.log('task run from queue', this.currentTasks, this.taskQueue);
}
}
}
// Example code
// Example Task function
function exampleSimpleTask(done) {
setTimeout(done, Math.random() * 1000);
}
var taskRunner = new TaskRunner(3);
// Use the exampleSimpleTask from above;
taskRunner.run(exampleSimpleTask); // Executes immediately
taskRunner.run(exampleSimpleTask); // Executes immediately
taskRunner.run(exampleSimpleTask); // Executes immediately
taskRunner.run(exampleSimpleTask); // Should wait until one of the running tasks completes
taskRunner.run(exampleSimpleTask); // Should wait until one of the running tasks completes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment