Heap.js

2.7.1 · active · verified Sun Apr 19

heap-js is an efficient JavaScript/TypeScript library providing a binary heap data structure, often used as a priority queue. It offers interfaces familiar to developers accustomed to Python's `heapq` module and Java's `PriorityQueue`, making it versatile for various algorithm implementations. The library is actively maintained, with the current stable version being 2.7.1, and receives frequent minor updates focusing on performance enhancements and new features like the `HeapAsync` class for asynchronous operations and comparators. Key differentiators include its robust performance, comprehensive testing, and support for both synchronous and asynchronous heap management, allowing it to handle complex prioritization logic. Instances default to an integer min-heap, with full customization options available for element comparison, aiming to be significantly faster than array sorting for common push/pop/peek operations in many scenarios.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic synchronous and asynchronous heap usage, including number and object heaps with custom comparators. It shows instantiation, pushing elements, peeking at the top element, and popping.

import { Heap, HeapAsync } from 'heap-js';

// 1. Basic synchronous min-heap for numbers
const minHeap = new Heap<number>();
minHeap.push(5);
minHeap.push(3);
minHeap.push(8);
console.log('Min-Heap peek:', minHeap.peek()); // Expected: 3
console.log('Min-Heap pop:', minHeap.pop()); // Expected: 3
console.log('Min-Heap elements:', minHeap.toArray()); // Expected: [5, 8]

// 2. Custom synchronous max-heap for objects
interface Task {
  priority: number;
  name: string;
}
// The comparator function defines the order: (a, b) => a - b for min-heap, b - a for max-heap
const maxHeap = new Heap<Task>((a, b) => b.priority - a.priority); // Max-heap comparator
maxHeap.push({ priority: 10, name: 'High Priority' });
maxHeap.push({ priority: 5, name: 'Medium Priority' });
maxHeap.push({ priority: 15, name: 'Critical Task' });
console.log('Max-Heap peek:', maxHeap.peek()?.name); // Expected: Critical Task

// 3. Example with HeapAsync for asynchronous comparisons or operations
// Requires an async comparator and awaits for heap methods
const asyncHeap = new HeapAsync<string>(async (a, b) => {
  await new Promise(resolve => setTimeout(resolve, 10)); // Simulate async work
  return a.length - b.length; // Sort by string length (min-heap)
});

async function runAsyncHeap() {
  await asyncHeap.push('apple');
  await asyncHeap.push('banana');
  await asyncHeap.push('kiwi');
  console.log('Async Heap peek:', await asyncHeap.peek()); // Expected: kiwi
  console.log('Async Heap size:', asyncHeap.size());
}

runAsyncHeap();

view raw JSON →