Last active
November 22, 2019 21:34
-
-
Save alex-taxiera/d6f056c6caaaf26f1a87d653fae04af5 to your computer and use it in GitHub Desktop.
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
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