@figliolia/data-structures
Version:
Efficient data structures for every day programming
66 lines (65 loc) • 1.58 kB
JavaScript
/**
* Heap
*
* The base construct of the MinHeap and MaxHeap utilities
*/
export class Heap {
storage = [];
valueExtractor;
constructor(valueExtractor) {
this.valueExtractor = valueExtractor;
}
/**
* Push
*
* Adds an element to the heap and positions it correctly
*/
push(value) {
this.storage.push(value);
let curr = this.length - 1;
while (curr > 0) {
const parent = (curr - 1) >>> 1;
if (this.comparer(curr, parent)) {
break;
}
this.swap(curr, parent);
curr = parent;
}
}
/**
* Pop
*
* Removes the last element in the heap
*/
pop() {
const N = this.length - 1;
this.swap(0, N);
const value = this.storage.pop();
let curr = 0;
let left = 0;
while ((left = 2 * curr + 1) < this.length) {
const minChildIndex = this.nextChild(left, left + 1);
if (this.comparer(minChildIndex, curr)) {
break;
}
this.swap(minChildIndex, curr);
curr = minChildIndex;
}
return value;
}
get length() {
return this.storage.length;
}
swap(index1, index2) {
[this.storage[index1], this.storage[index2]] = [
this.storage[index2],
this.storage[index1],
];
}
extract(value) {
if (typeof value === "number") {
return value;
}
return this.valueExtractor(value);
}
}