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.
npm install heap-jsVerified import paths — ran on the pinned version, not inferred.
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.
If a fully sorted list of the top N elements is required, you must sort the result of `top(N)` manually after retrieval, e.g., `heap.top(N).sort(heap.comparator)`.
Do not rely on the order of elements when using `heap.iterator()`. If you need ordered access, use `pop()` repeatedly (which consumes the heap) or `toArray()` followed by a sort.
If you need to iterate without modifying the heap, convert it to an array first (e.g., `[...heap.toArray()]`) or use `toArray()` directly. Only iterate directly if emptying the heap is the desired outcome.
Review your comparator function carefully. For TypeScript, ensure `Comparator<T>` type is correctly implemented. For objects, compare a specific property: `(a, b) => a.property - b.property`.
For ES Modules in Node.js or browser, use `import { Heap } from 'heap-js';`. If stuck with CommonJS, consider using dynamic import `import('heap-js').then(module => new module.Heap())` or ensure your build system correctly transpiles ESM imports.If a fully sorted list of the top N elements is required, explicitly sort the result: `const topSorted = heap.top(N).sort(heap.comparator);`.
If you need to iterate without modifying the heap, first convert it to an array: `for (const item of myHeap.toArray()) { ... }`. Only use direct iteration if you intend to empty the heap.No dependency data recorded yet.