Skip to content

Instantly share code, notes, and snippets.

@alex-taxiera
Last active November 22, 2019 21:34
Show Gist options
  • Save alex-taxiera/d6f056c6caaaf26f1a87d653fae04af5 to your computer and use it in GitHub Desktop.
Save alex-taxiera/d6f056c6caaaf26f1a87d653fae04af5 to your computer and use it in GitHub Desktop.
const { EventEmitter } = require('events')
class PriorityJobQueue extends EventEmitter {
constructor (levels, ...rest) {
super(...rest)
this.queues = new Array(levels).fill([])
this.currentJob = null
this.totalJobs = 0
}
get length () {
return this.queues.reduce((ax, dx) => ax + dx.length, 0)
}
push (job, priority = 0) {
const id = ++this.totalJobs
this.queues[priority].push({ id, job })
this.checkQueue()
return id
}
checkQueue () {
if (!this.shouldRun) return
for (const queue of this.queues) {
if (queue.length > 0) {
this.currentJob = queue.shift()
break
}
}
this.run()
}
get shouldRun () {
return !this.currentJob && this.length > 0
}
async run () {
const { id, job } = this.currentJob
try {
const data = await job()
this.emit('jobSuccess', id, data)
} catch (error) {
this.emit('jobError', id, error)
}
this.currentJob = null
this.checkQueue()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment