Skip to content

Instantly share code, notes, and snippets.

@thebiltheory
Created November 5, 2017 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebiltheory/a430b7983cbecb77e9c4cc1a007832ca to your computer and use it in GitHub Desktop.
Save thebiltheory/a430b7983cbecb77e9c4cc1a007832ca to your computer and use it in GitHub Desktop.
A minimal implementation of a priority queue. All I needed.
/** 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