Fast Heap-based Priority Queue

0.8.0 · active · verified Wed Apr 22

FastPriorityQueue.js is a high-performance, heap-based priority queue implementation for JavaScript and TypeScript. It provides efficient O(log n) operations for adding and polling elements, and O(1) for peeking the smallest element. The package is currently at version 0.8.0 and maintains an active development status, with recent minor releases addressing bug fixes and performance optimizations. Its primary differentiator is its focus on raw performance, often outperforming other JavaScript priority queue libraries by a significant margin, making it ideal for applications where the speed of data structure operations is critical. It ships with TypeScript types, ensuring a robust developer experience in typed environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionality of FastPriorityQueue, including adding elements, peeking at the top element, checking the queue size, and polling elements. It also illustrates how to create a max-priority queue using a custom comparator function.

import FastPriorityQueue from 'fastpriorityqueue';

// Create a default min-priority queue
const pqMin = new FastPriorityQueue();
pqMin.add(1);
pqMin.add(0);
pqMin.add(5);
pqMin.add(4);
pqMin.add(3);

console.log('Min-Priority Queue - Peek:', pqMin.peek()); // Should return 0
console.log('Min-Priority Queue - Size:', pqMin.size); // Should return 5

// Create a max-priority queue using a custom comparator
const pqMax = new FastPriorityQueue(function(a, b) {
  return a > b; // Returns true if a has higher priority (is 'larger') than b
});
pqMax.add(1);
pqMax.add(0);
pqMax.add(5);
pqMax.add(4);
pqMax.add(3);

console.log('\nElements from Min-Priority Queue (poll):');
while (!pqMin.isEmpty()) {
  console.log(pqMin.poll()); // Will print 0 1 3 4 5
}

console.log('\nElements from Max-Priority Queue (poll):');
while (!pqMax.isEmpty()) {
  console.log(pqMax.poll()); // Will print 5 4 3 1 0
}

pqMin.trim(); // Optional: optimizes memory usage after churn

view raw JSON →