Skip to content

Instantly share code, notes, and snippets.

@vjrngn
Created January 10, 2019 06:04
Show Gist options
  • Save vjrngn/5c223afa6840b8d11752aae092d23ab4 to your computer and use it in GitHub Desktop.
Save vjrngn/5c223afa6840b8d11752aae092d23ab4 to your computer and use it in GitHub Desktop.
A priority queue implementation is JS
class Node {
constructor (value, priority) {
this.value = value;
this.priority = priority;
}
}
class PriorityQueue {
constructor () {
this.heap = [null];
}
insert (value, priority) {
const newNode = new Node(value, priority);
this.heap.push(newNode);
let currentNodeIndex = this.heap.length - 1;
let currentNodeParentIndex = Math.floor(currentNodeIndex / 2);
while (this.heap[currentNodeParentIndex] && newNode.priority > this.heap[currentNodeParentIndex].priority) {
const parent = this.heap[currentNodeParentIndex];
this.heap[currentNodeParentIndex] = newNode;
this.heap[currentNodeIndex] = parent;
currentNodeIndex = currentNodeParentIndex;
currentNodeParentIndex = Math.floor(currentNodeIndex / 2);
}
}
remove() {
const toRemove = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIndex = 1;
const [left, right] = [2 * currentIndex, 2 * currentIndex + 1];
let currentChildIndex = this.heap[right] && this.heap[right].priority >= this.heap[left].priorty ? right : left;
while (this.heap[currentChildIndex] && this.heap[currentIndex].priority <= this.heap[currentChildIndex].priority) {
let currentNode = this.heap[currentIndex];
let currentChildNode = this.heap[currentChildIndex];
this.heap[currentChildIndex] = currentNode;
this.heap[currentIndex] = currentChildNode;
}
return toRemove;
}
peek() {
return this.heap[1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment