{"id":11028,"library":"heap-js","title":"Heap.js","description":"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.","status":"active","version":"2.7.1","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/ignlg/heap-js","tags":["javascript","heap","binary heap","priority queue","tree","binary tree","data structure","algorithm","typescript"],"install":[{"cmd":"npm install heap-js","lang":"bash","label":"npm"},{"cmd":"yarn add heap-js","lang":"bash","label":"yarn"},{"cmd":"pnpm add heap-js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary synchronous heap class. While CommonJS `require` might work for some bundlers, native Node.js ESM requires `import`.","wrong":"const Heap = require('heap-js'); // Incorrect for modern CJS setups, use dynamic import or 'import type'","symbol":"Heap","correct":"import { Heap } from 'heap-js';"},{"note":"Introduced in v2.3.0 for heaps with async comparators or async operations. Requires `await` for methods like `push` and `peek`.","wrong":"const HeapAsync = require('heap-js').HeapAsync;","symbol":"HeapAsync","correct":"import { HeapAsync } from 'heap-js';"},{"note":"This is a TypeScript type for defining custom comparison functions. Use `import type` to avoid importing a runtime value.","wrong":"import { Comparator } from 'heap-js';","symbol":"Comparator","correct":"import type { Comparator } from 'heap-js';"}],"quickstart":{"code":"import { Heap, HeapAsync } from 'heap-js';\n\n// 1. Basic synchronous min-heap for numbers\nconst minHeap = new Heap<number>();\nminHeap.push(5);\nminHeap.push(3);\nminHeap.push(8);\nconsole.log('Min-Heap peek:', minHeap.peek()); // Expected: 3\nconsole.log('Min-Heap pop:', minHeap.pop()); // Expected: 3\nconsole.log('Min-Heap elements:', minHeap.toArray()); // Expected: [5, 8]\n\n// 2. Custom synchronous max-heap for objects\ninterface Task {\n  priority: number;\n  name: string;\n}\n// The comparator function defines the order: (a, b) => a - b for min-heap, b - a for max-heap\nconst maxHeap = new Heap<Task>((a, b) => b.priority - a.priority); // Max-heap comparator\nmaxHeap.push({ priority: 10, name: 'High Priority' });\nmaxHeap.push({ priority: 5, name: 'Medium Priority' });\nmaxHeap.push({ priority: 15, name: 'Critical Task' });\nconsole.log('Max-Heap peek:', maxHeap.peek()?.name); // Expected: Critical Task\n\n// 3. Example with HeapAsync for asynchronous comparisons or operations\n// Requires an async comparator and awaits for heap methods\nconst asyncHeap = new HeapAsync<string>(async (a, b) => {\n  await new Promise(resolve => setTimeout(resolve, 10)); // Simulate async work\n  return a.length - b.length; // Sort by string length (min-heap)\n});\n\nasync function runAsyncHeap() {\n  await asyncHeap.push('apple');\n  await asyncHeap.push('banana');\n  await asyncHeap.push('kiwi');\n  console.log('Async Heap peek:', await asyncHeap.peek()); // Expected: kiwi\n  console.log('Async Heap size:', asyncHeap.size());\n}\n\nrunAsyncHeap();","lang":"typescript","description":"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."},"warnings":[{"fix":"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)`.","message":"The `top(N)` method no longer guarantees a sorted output for the N elements. Only the first element (index 0) is guaranteed to be the top priority element. The remaining N-1 elements are only partially ordered.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"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.","message":"The `.iterator()` method, similar to Java's `PriorityQueue` implementation, does not guarantee to traverse elements in any particular order. The order of elements returned by the iterator is arbitrary.","severity":"gotcha","affected_versions":">=2.2.0"},{"fix":"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.","message":"Directly using a heap instance as an iterator (e.g., in a `for...of` loop) will consume (empty) the heap, similar to Python's `heapq` behavior. This is because each iteration will `pop` an element.","severity":"gotcha","affected_versions":">=2.2.0"},{"fix":"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`.","message":"When defining custom comparators, ensure they return a number: `a - b` for min-heap (ascending order), or `b - a` for max-heap (descending order). Incorrect comparator logic can lead to an invalid heap state.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"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.","cause":"Attempting to use `require('heap-js')` in a CommonJS module with a package primarily designed for ES Modules, or incorrect destructuring.","error":"TypeError: Cannot read properties of undefined (reading 'Heap') OR TypeError: Heap is not a constructor"},{"fix":"If a fully sorted list of the top N elements is required, explicitly sort the result: `const topSorted = heap.top(N).sort(heap.comparator);`.","cause":"Misunderstanding the behavior of `heap.top(N)` method after version 2.0.0, which explicitly states the output is not fully sorted.","error":"Expected top(N) to return sorted elements, but they are out of order."},{"fix":"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.","cause":"Direct iteration over a `Heap` instance (e.g., `for (const item of myHeap)`) consumes the heap by repeatedly calling `pop()`.","error":"My for...of loop on the heap emptied it out unexpectedly."}],"ecosystem":"npm"}