A javascript binary heap implementation
$ npm install bheap
var BinaryHeap = require('bheap') var heap = new BinaryHeap((a, b) => a.diameter - b.diameter) heap.push({ diameter: 4878, name: 'Mercury' }) heap.push({ diameter: 139822, name: 'Jupiter' }) heap.push({ diameter: 12104, name: 'Venus' }) heap.size // 3 heap.top() // { diameter: 300, name: 'Jupiter' } heap.pop() // { diameter: 300, name: 'Jupiter' } heap.size // 2
It creates a BinaryHeap instance based on comparator order and filled with array elements. The top element of the binary heap is the maximum based on comparator
Time complexity: O(n) such that n === array.length
- Type: Function
- Returns:
- positive if
ais greater thanb - negative if
ais less thanb - zero if
ais equal tob
- positive if
- Type: Array
- Default: []
Elements that are inserted in binary heap.
- Type: Function
- Returns: Element of
BinaryHeapinstance
Gets the top element of the binary heap.
Returns undefined when the heap is empty.
Time complexity: O(1)
- Type: Function
- Returns: Element of instance of
BinaryHeap
Pops the top element of instance of binary heap.
Returns undefined when the heap is empty.
Time complexity: O(log(n)) such that n === this.size
- Type: Function
- Returns: Integer
Push the element at the binary heap and returns its new size.
Time complexity: O(log(n)) such that n === this.size
I wanted to keep the ECMAScript 6 conventions.
I preferred intuitive API for javascript developers. Thus, I wanted to keep the same behaviour that other data structures as Array. An empty array does not throw an error when pop or shift is called. BinaryQueue neither.
$ npm test
MIT