Back to The Haunt
The craft3 min read

JavaScript has no priority queue. Write one.

JavaScript has no built-in priority queue or heap: not in browsers, and not in Node.js. The tempting replacement is to push into an array and sort it each time, which costs O(n log n) per insert. A binary heap stored in a plain array does each push and pop in O(log n), and it fits in about forty lines.

A heap with a comparator

class PriorityQueue {
  constructor(before = (a, b) => a < b) {
    this.heap = [];
    this.before = before; // true when a should come out first
  }
  get size() { return this.heap.length; }
  peek() { return this.heap[0]; }
  push(item) {
    const h = this.heap;
    h.push(item);
    let i = h.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!this.before(h[i], h[parent])) break;
      [h[i], h[parent]] = [h[parent], h[i]];
      i = parent;
    }
  }
  pop() {
    const h = this.heap;
    const top = h[0];
    const last = h.pop();
    if (h.length > 0) {
      h[0] = last;
      let i = 0;
      while (true) {
        const l = 2 * i + 1, r = l + 1;
        let best = i;
        if (l < h.length && this.before(h[l], h[best])) best = l;
        if (r < h.length && this.before(h[r], h[best])) best = r;
        if (best === i) break;
        [h[i], h[best]] = [h[best], h[i]];
        i = best;
      }
    }
    return top;
  }
}
const min = new PriorityQueue();
for (const x of [5, 2, 8, 4]) min.push(x);
console.log(min.pop(), min.pop(), min.size); // 2 4 2
const max = new PriorityQueue((a, b) => a > b);
for (const x of [5, 2, 8, 4]) max.push(x);
console.log(max.pop(), max.peek()); // 8 5
const jobs = new PriorityQueue((a, b) => a.due < b.due);
jobs.push({ name: 'ship', due: 5 });
jobs.push({ name: 'write', due: 1 });
console.log(jobs.pop().name); // write

How it works

The array is a complete binary tree: the children of index i sit at 2i + 1 and 2i + 2, and its parent at (i - 1) >> 1. Each parent comes out before its children, so the front item is always at index 0.

  • `push` adds the item at the end and swaps it up while it beats its parent.
  • `pop` takes index 0, moves the last item into its place, and swaps it down with the better child until neither child beats it.

Both follow one path through a tree of height about log₂ n. peek is O(1), and popping an empty queue returns undefined.

The comparator answers "should a come out before b?". Use a < b for a min-heap, a > b for a max-heap, or compare a field for objects. Avoid writing it as a - b, the style sort uses: that returns a number, and this class expects true or false.

Things to know

  • The array is not sorted. [2, 4, 8, 5] is a valid min-heap. Pop items one by one to get them in order.
  • Equal priorities come out in no fixed order. If ties must keep arrival order, store a sequence number and compare it when priorities are equal.
  • LeetCode is the exception. Its JavaScript runtime preloads a priority queue library, which is why MinPriorityQueue works there and nowhere else. Interviews in a plain editor or Node.js need your own.

Chapter 10 of our free JavaScript for DSA book builds a stable min-priority queue this way, with sequence numbers for ties, and later chapters use it. If you also write Go, its standard library has container/heap, and Go for DSA shows how to use it.

That’s it. Come back soon; the ghost keeps writing.Follow by RSS

Read next.