TinyQueue is a minimal binary heap priority queue. By default, it implements a min-heap (the smallest value is popped first). You can initialize it with an empty constructor, an existing array (which will be modified in-place), or a custom comparator function for non-numeric or complex object sorting.
Core Methods
push(item): Adds an item to the queue.pop(): Removes and returns the top item (the smallest according to the comparator).peek(): Returns the top item without removing it.length: A property representing the number of items in the queue.
Custom Comparators
To handle objects or custom sorting logic, pass a comparator function as the second argument to the constructor. The comparator should follow the standard (a, b) => number pattern (returning a negative value if a < b, zero if a === b, and a positive value if a > b).
// Basic usage with numbers
let queue = new TinyQueue();
queue.push(7);
queue.push(5);
queue.push(10);
let top = queue.pop(); // returns 5
top = queue.peek(); // returns 7
console.log(queue.length); // returns 2
// Initialize from an existing array (modifies the array)
let arr = [7, 5, 10];
let queueFromArray = new TinyQueue(arr);
// Usage with custom objects and a comparator
let objectQueue = new TinyQueue([{value: 5}, {value: 7}], function (a, b) {
return a.value - b.value;
});
// Converting a queue to a sorted array
const sortedArray = [];
while (objectQueue.length) sortedArray.push(objectQueue.pop());