TinyQueue: Smallest JavaScript Priority Queue

3.0.0 · active · verified Sun Apr 19

tinyqueue is a lightweight, efficient JavaScript library providing a binary heap-based priority queue data structure. Currently at version 3.0.0, it offers fundamental operations like `push`, `pop`, and `peek` with minimal overhead. The library's core design prioritizes simplicity and a small bundle size, distinguishing it from more feature-rich or specialized queue implementations. It supports custom comparison functions, allowing users to define priority based on object properties rather than just raw values. While release cadence is not strictly regular, it sees updates for performance improvements and compatibility, with the most recent major update (v3.0.0) shifting to an ES module-only distribution.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize a TinyQueue, add elements, retrieve the highest priority item, inspect the queue's length, and use custom comparators for complex objects, including how to turn a queue into a sorted array.

import TinyQueue from 'tinyqueue';

// Create an empty priority queue
const queue = new TinyQueue();

// Add some items
queue.push(7);
queue.push(5);
queue.push(10);

console.log('Initial top item:', queue.peek()); // Expected: 5

// Remove the top item
const top = queue.pop(); // Returns 5
console.log('Popped item:', top);
console.log('Current top item:', queue.peek()); // Expected: 7
console.log('Queue length:', queue.length); // Expected: 2

// Create a priority queue from an existing array
const initialArrayQueue = new TinyQueue([7, 5, 10]);
console.log('Queue from array, top:', initialArrayQueue.peek()); // Expected: 5

// Pass a custom item comparator for objects
const customQueue = new TinyQueue([{value: 5}, {value: 7}, {value: 3}], function (a, b) {
    return a.value - b.value;
});
console.log('Custom queue top item value:', customQueue.peek().value); // Expected: 3

// Turn a queue into a sorted array by repeatedly popping
const sortedArray = [];
while (customQueue.length) {
    sortedArray.push(customQueue.pop().value);
}
console.log('Sorted array from queue:', sortedArray); // Expected: [3, 5, 7]

view raw JSON →