Skip to content

Instantly share code, notes, and snippets.

@afterburn
Last active January 25, 2019 13:28
Show Gist options
  • Save afterburn/cf31226a670399ab33ce76d6aa2886bc to your computer and use it in GitHub Desktop.
Save afterburn/cf31226a670399ab33ce76d6aa2886bc to your computer and use it in GitHub Desktop.
Queue implementation in JavaScript
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()
}
}
}
}
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