Binary min-heap queue with in-place update and removal
A build scheduler keeps a queue of jobs. The job with the most urgent priority runs next, but priorities change while jobs wait: a user bumps a hotfix to the front, or a flaky job is pushed back. Jobs can also be cancelled before they run. Re-sorting the whole queue on every change is too slow, so the scheduler needs a heap that can find and fix any item in place.
Implement a class PriorityQueue backed by a binary min-heap.
const queue = new PriorityQueue();
queue.push(item, priority); // => new size
queue.peek(); // => next item, or undefined
queue.pop(); // => removes and returns the next item, or undefined
queue.size(); // => number of queued items
queue.has(item); // => boolean
queue.update(item, priority); // => true if the item was queued, else false
queue.remove(item); // => true if the item was queued, else false
update changes an item’s priority but keeps its original push order for tie-breaking.Map). Two different objects with the same contents are different items.push throws an Error if the item is already queued.peek and pop return undefined when the queue is empty.update and remove return false and change nothing when the item is not queued.push, pop, update, and remove must run in O(log n). peek, size, and has run in O(1).const jobs = new PriorityQueue();
jobs.push('deploy', 3); // => 1
jobs.push('lint', 2); // => 2
jobs.push('test', 2); // => 3
jobs.push('docs', 5); // => 4
jobs.peek(); // => 'lint' (tie with 'test', pushed first)
jobs.update('docs', 1); // => true
jobs.remove('test'); // => true
jobs.remove('test'); // => false
jobs.pop(); // => 'docs'
jobs.pop(); // => 'lint'
jobs.pop(); // => 'deploy'
jobs.pop(); // => undefined
jobs.size(); // => 0
Hint: a heap alone cannot find an arbitrary item quickly. Keep a Map from each item to its current index in the heap array, and update it on every swap.