Implement a priority queue with a binary heap
Implement a priority queue in JavaScript with a binary heap, so push and pop take logarithmic time, with a comparator for any item shape.
Task schedulers and shortest-path searches need the smallest item next. Sorting after every insert is wasteful. A binary heap stored in an array keeps the smallest item at index 0.
class PriorityQueue {
#heap = [];
constructor(compare = (a, b) => a - b) {
this.compare = compare;
}
push(value) {
const heap = this.#heap;
heap.push(value);
let i = heap.length - 1;
while (i > 0) {
const parent = (i - 1) >> 1;
if (this.compare(heap[i], heap[parent]) >= 0) break;
[heap[i], heap[parent]] = [heap[parent], heap[i]];
i = parent;
}
}
pop() {
const heap = this.#heap;
if (heap.length === 0) return undefined;
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
for (;;) {
const left = 2 * i + 1;
const right = left + 1;
let smallest = i;
if (left < heap.length && this.compare(heap[left], heap[smallest]) < 0) smallest = left;
if (right < heap.length && this.compare(heap[right], heap[smallest]) < 0) smallest = right;
if (smallest === i) break;
[heap[i], heap[smallest]] = [heap[smallest], heap[i]];
i = smallest;
}
}
return top;
}
}
const queue = new PriorityQueue((a, b) => a.priority - b.priority);
queue.push({ task: 'deploy', priority: 3 });
queue.push({ task: 'fix', priority: 1 });
queue.push({ task: 'review', priority: 2 });
console.log(queue.pop().task, queue.pop().task, queue.pop().task);fix review deployA parent sits at index (i - 1) >> 1 and its children at 2i + 1 and 2i + 2, so the tree needs no pointers. push moves the new item up, and pop moves the replacement down, each in a number of steps proportional to the height of the tree.
Items with equal priority come out in no guaranteed order. If you need first in, first out among equals, add a counter to the comparison.