I'm trying to implement a remove method for my binary heap implementation.
class Node {
constructor(priority) {
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.heap = [null];
}
remove() {
const toRemove = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIdx = 1;
let [left, right] = [2*currentIdx, 2*currentIdx + 1];
let currentChildIdx = this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left; //Assess which child node has higher priority
while (this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority) {
let currentNode = this.heap[currentIdx]
let currentChildNode = this.heap[currentChildIdx];
this.heap[currentChildIdx] = currentNode;
this.heap[currentIdx] = currentChildNode;
currentIdx = this.heap.indexOf(currentNode);
}
return toRemove;
}
}
However, I'm not sure how to properly update the value of currentIdx and currentChildIdx when I'm running my while loop. In fact, the code seems to stop working when I try to update the value of currentIdx
currentIdx = this.heap.indexOf(currentNode);
Any tips on what I'm doing wrong?
Full code here: https://repl.it/@Stylebender/Binary-Heap-Naive