Write a Priority Queue Class with a Comparator
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write a class PriorityQueue<T> whose constructor takes a comparator compare(a, b), negative when a comes first, as Array.prototype.sort expects. push(item) adds an item, pop() removes and returns the one that comes first (the smallest), peek() returns it without removing it, both return undefined when the queue is empty, and size is the number of items. Use a binary heap or anything else that keeps the order. Type it so T is inferred from the comparator, the comparator gets two Ts, and pushing anything else is rejected.
Your code must pass
- Pops numbers smallest first
- Orders objects with the comparator
- Returns undefined when empty
- Has no type errors
- Infers T from the comparator
- The comparator gets two Ts
- Rejects pushing the wrong type