Created
November 5, 2017 13:51
-
-
Save thebiltheory/a430b7983cbecb77e9c4cc1a007832ca to your computer and use it in GitHub Desktop.
A minimal implementation of a priority queue. All I needed.
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
/** Minimalist Priority Queue. */ | |
export default class PriorityQueue { | |
constructor() { | |
this.nodes = []; | |
} | |
/** | |
* Enqueue a new element to the Queue | |
* @param {value} key value of the key item | |
* @param {number} priority set the priority of the item | |
*/ | |
enqueue(key, priority) { | |
this.nodes.push({ key, priority }); | |
this.sort(); | |
} | |
/** | |
* Dequeue the first element | |
* @return {value} | |
*/ | |
dequeue() { | |
return this.nodes.shift().key; | |
} | |
/** | |
* Sort the node Queue | |
*/ | |
sort() { | |
this.nodes.sort((a, b) => a.priority - b.priority); | |
} | |
/** | |
* Sort the node Queue | |
* @return {Boolean} | |
*/ | |
isEmpty() { | |
return !this.nodes.length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment