Gathering detailed insights and metrics for heap-js
Gathering detailed insights and metrics for heap-js
Gathering detailed insights and metrics for heap-js
Gathering detailed insights and metrics for heap-js
Efficient Binary heap (priority queue, binary tree) data structure for JavaScript / TypeScript. Includes JavaScript methods, Python's heapq module methods, and Java's PriorityQueue methods.
npm install heap-js
99.5
Supply Chain
99.6
Quality
76.9
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
122 Stars
237 Commits
8 Forks
1 Watching
2 Branches
1 Contributors
Updated on 26 Nov 2024
TypeScript (94.64%)
JavaScript (5.36%)
Cumulative downloads
Total Downloads
Last day
-3.4%
247,356
Compared to previous day
Last week
5.9%
1,394,874
Compared to previous week
Last month
7.6%
5,641,439
Compared to previous month
Last year
91.1%
55,831,755
Compared to previous year
27
Efficient Binary heap (priority queue, binary tree) data structure for JavaScript / TypeScript.
Now with support for async comparators with the new HeapAsync
class!
Includes JavaScript methods, Python's heapq module methods, and Java's PriorityQueue methods.
Easy to use, known interfaces, tested, and well-documented JavaScript binary heap library.
Instances are integer min heap
by default.
It depends on your usage, but for some scenarios, it is much faster:
heap vs array: push + pop/unshift 50
heap x 72,130 ops/sec ±0.50% (93 runs sampled)
array x 121 ops/sec ±78.09% (5 runs sampled)
heap vs array: push + peek 20
heap x 622,332 ops/sec ±27.93% (63 runs sampled)
array x 207 ops/sec ±78.18% (5 runs sampled)
heap vs array: push + top(1) of 100
heap x 124,835 ops/sec ±40.37% (61 runs sampled)
array x 123 ops/sec ±78.49% (5 runs sampled)
heap vs array: push + top(50) of 100
heap x 59,210 ops/sec ±17.66% (82 runs sampled)
array x 125 ops/sec ±78.79% (5 runs sampled)
limit
property to support negative, Infinity, and NaN values. They will be set as 0
and the heap will not be limited.setLimit
method to set the limit of the heap. It returns NaN
if the limit is negative, or NaN. This method is useful to check if the limit was set as expected.indexOf
method to find the first index of an element in the heap.indexOfEvery
method to find all indexes of an element in the heap.remove
method to use the indexOf
method.contains
method to use the indexOf
method.HeapAsync
class, with async methods and supporting async comparators. It is a drop-in replacement for the Heap
class with Promises..iterator()
method to follow Java's PriorityQueue implementation:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
Notice that using the heap directly as an iterator will consume the heap, as Python's heapq
implementation does.
Heap.nlargest
as in heapq
.Heap.nsmallest
as in heapq
.top
/ bottom
input to force an integer.The main breaking change is that now top(N)
does NOT sort the output, because sorting should not be part of the spec for a priority queue. The output is the top N elements, and they will be partially ordered with the peek at index 0
by definition.
top(N)
is unordered, only the first element is guaranteed to be the top priority element.top(N)
algorithms.Iterator
interface and iterator()
method.A heap where the smallest element is always at the top. It is the default heap.
1import { Heap } from 'heap-js'; 2 3// Min Heap by default 4const minHeap = new Heap(); 5 6// Initialize the heap with an array 7minHeap.init([5, 18, 1]); 8// Push a new value 9minHeap.push(2); 10 11console.log(minHeap.peek()); //> 1 12console.log(minHeap.pop()); //> 1 13console.log(minHeap.peek()); //> 2
A heap where the largest element is always at the top.
1import { Heap } from 'heap-js'; 2 3// Max Heap 4const maxHeap = new Heap(Heap.maxComparator); 5 6// Initialize the heap with an array 7maxHeap.init([3, 4, 1, 12, 8]); 8// Push a new value 9maxHeap.push(2); 10 11console.log(maxHeap.peek()); //> 12 12console.log(maxHeap.pop()); //> 12 13console.log(maxHeap.peek()); //> 8
A heap where the most important element is always at the top, but the elements are objects with a priority
property.
1import { Heap } from 'heap-js'; 2 3const customPriorityComparator = (a, b) => a.priority - b.priority; 4// Custom Heap 5const customHeap = new Heap(customPriorityComparator); 6 7// Initialize the heap with an array 8customHeap.init([{ priority: 5 }, { priority: 18 }, { priority: 1 }]); 9// Push a new value 10customHeap.push({ priority: 2 }); 11 12console.log(customHeap.peek()); //> { priority: 1 } 13console.log(customHeap.pop()); //> { priority: 1 } 14console.log(customHeap.peek()); //> { priority: 2 }
A heap where the most important element is always at the top, the elements are objects with a priority
property, and the comparator function is asynchronous. Implements the same interface as Heap
, but almost all methods return a Promise
.
1import { HeapAsync } from 'heap-js'; 2 3const customPriorityComparator = (a, b) => Promise.resolve(a.priority - b.priority); 4// Custom HeapAsync 5const customHeap = new HeapAsync(customPriorityComparator); 6 7// Initialize the heap with an array 8await customHeap.init([{ priority: 5 }, { priority: 18 }, { priority: 1 }]); 9// Push a new value 10await customHeap.push({ priority: 2 }); 11 12console.log(customHeap.peek()); //> { priority: 1 } 13console.log(await customHeap.pop()); //> { priority: 1 } 14console.log(await customHeap.peek()); //> { priority: 2 }
Iterates over the heap consuming it, and guarantees to traverse the elements of the heap in the order of priority. Useful.
1const { Heap } = require('heap-js'); 2 3// Get all tasks from the database 4const tasks = db.collection.find().toArray(); 5// The most important task has the lowest priority value 6const customPriorityComparator = (a, b) => a.priority - b.priority; 7 8// Create the priority queue 9const priorityQueue = new Heap(customPriorityComparator); 10// Initialize the priority queue with the tasks 11priorityQueue.init(tasks); 12 13// Iterator that will consume the heap while traversing it in the order of priority 14for (const task of priorityQueue) { 15 console.log(task); 16}
Iterates over the heap without consuming it, but does not guarantee to traverse the elements of the heap in any particular order. Barely useful.
1const { Heap } = require('heap-js'); 2 3// Get all tasks from the database 4const tasks = db.collection.find().toArray(); 5// The most important task has the lowest priority value 6const customPriorityComparator = (a, b) => a.priority - b.priority; 7 8const priorityQueue = new Heap(customPriorityComparator); 9// Initialize the priority queue with the tasks 10priorityQueue.init(tasks); 11 12// Iterator, the Java way, that will not consume the heap BUT does not guarantee to traverse the elements of the heap in any particular order. Barely useful. 13for (const task of priorityQueue.iterator()) { 14 console.log(task); 15}
1import { Heap } from 'heap-js'; 2const numbers = [2, 3, 7, 5]; 3 4// Changes the array elements order into a heap in-place 5Heap.heapify(numbers); 6console.log(numbers); //> [ 2, 3, 5, 7 ] 7 8// Pushes a new value to the heap 9Heap.heappush(numbers, 1); 10console.log(numbers); //> [ 1, 2, 5, 7, 3 ]
1yarn add heap-js # if you use yarn 2 3npm install --save heap-js # if you use npm
1new Heap([comparator]);
1new HeapAsync([asyncComparator]);
Heap.minComparator
: Uses less-than operator to compare elements. It is the default comparator.Heap.maxComparator
: Uses greater-than operator to compare elements.Heap.minComparatorNumber
: Uses subtraction a - b
to compare elements.Heap.maxComparatorNumber
: Uses subtraction b - a
to compare elements.for (const value of heap)
directly usable as an Iterator, consumes the heap.length
of the heap.limit
the number of elements in the heap.pop()
the top element.push(...elements)
one or more elements to the heap.pushpop(element)
faster than push
& pop
.replace(element)
faster than pop
& push
.top(number?)
most valuable elements from the heap.bottom(number?)
least valuable elements from the heap.indexOf(element, fn?)
returns the internal index of the first occurrence of the element in the heap.indexOfEvery(element, fn?)
returns an array with the internal indexes of all occurrences of the element in the heap.PriorityQueue
interfaceadd(element)
to the heap.addAll([element, element, ... ])
to the heap, faster than loop add
.clear()
clone()
comparator()
contains(element, fn?)
element()
alias of peek()
isEmpty()
iterator()
returns the same as toArray()
because it is iterable and follows Java's implementation. Barely useful. Use for (const value of heap)
instead.offer(element)
alias of add(element)
peek()
poll()
alias of pop()
remove(element?)
removeAll()
alias of clear()
size()
alias of length
toArray()
toString()
To do:
containsAll
equals
retainAll
heapq
interfaceHeap.heapify(array, comparator?)
that converts an array to an array-heap.Heap.heappop(heapArray, comparator?)
that takes the peek of the array-heap.Heap.heappush(heapArray, item, comparator?)
that appends elements to the array-heap.Heap.heappushpop(heapArray, item, comparator?)
faster than heappush
& heappop
.Heap.heapreplace(heapArray, item, comparator?)
faster than heappop
& heappush
.Heap.nlargest(n, iterable, comparator?)
that gets the n
most valuable elements of an iterable.Heap.nsmallest(n, iterable, comparator?)
that gets the n
least valuable elements of an iterable.Extras:
Heap.heaptop(n, heapArray, comparator?)
that returns the n
most valuable elements of the array-heapHeap.heapbottom(n, heapArray, comparator?)
that returns the n
least valuable elements of the array-heapTo do:
merge(...iterables, comparator?)
https://ignlg.github.io/heap-js/
Development of Heap.js happens in the open on GitHub, and I am grateful to the community for contributing bug fixes and improvements.
1yarn
1npm run test
1npm run benchmarks
Heap.js is BSD licensed.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
7 existing vulnerabilities detected
Details
Reason
Found 0/9 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More