Last active
January 25, 2019 13:28
-
-
Save afterburn/cf31226a670399ab33ce76d6aa2886bc to your computer and use it in GitHub Desktop.
Queue implementation in JavaScript
This file contains hidden or 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 Queue { | |
constructor (onTaskComplete) { | |
this.tasks = [] | |
this.tasksCompleted = 0 | |
this.processing = false | |
this.onTaskComplete = onTaskComplete || (() => {}) | |
} | |
enqueue (task) { | |
this.tasks.push(task) | |
if (!this.processing) { | |
this.process() | |
} | |
} | |
dequeue () { | |
return this.tasks.shift() | |
} | |
process () { | |
if (!this.processing) { | |
while (this.tasks.length > 0) { | |
this.tryProcessNext() | |
} | |
} | |
} | |
tryProcessNext () { | |
this.processing = true | |
const task = this.dequeue() | |
if (task) { | |
if (typeof task === 'function') { | |
task((result) => { | |
this.tasksCompleted++ | |
this.onTaskComplete(result, this.tasksCompleted) | |
this.processing = false | |
this.process() | |
}) | |
} else { | |
this.tasksCompleted++ | |
this.onTaskComplete(task, this.tasksCompleted) | |
this.processing = false | |
this.process() | |
} | |
} | |
} | |
} |
This file contains hidden or 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
const q = new Queue(res => console.log(res)) | |
q.enqueue((next) => { | |
next('task 1') | |
}) | |
q.enqueue('task 2') | |
q.enqueue(next => { | |
setTimeout(() => { | |
next('task 3') | |
}, 1000) | |
}) | |
setTimeout(() => { | |
q.enqueue('task 4') | |
}, 500) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment