standard-data-structures
Version:
A collection of standard data-structures for node and browser
100 lines (99 loc) • 2.52 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A mutable MAX HEAP data-structure.
* It can also work as a min heap by inverting the `gt` parameter.
*/
class MaxHeap {
constructor(gt) {
this.gt = gt;
this.stack = new Array();
}
/**
* Creates a new [[MaxHeap]] data structure.
*/
static of(gt) {
return new MaxHeap(gt);
}
/**
* Creates a new MaxHeap that works with numbers
*/
static get numbers() {
return MaxHeap.of((a, b) => a > b);
}
/**
* Returns the size of the heap
*/
get length() {
return this.stack.length;
}
/**
* Returns the top most element on the heap
*/
get peek() {
if (this.stack.length > 0) {
return this.stack[0];
}
return undefined;
}
/**
* Remove the top element from heap.
*/
pop() {
if (this.stack.length > 0) {
this.swap(0, this.stack.length - 1);
const r = this.stack.pop();
this.heapD(0);
return r;
}
return undefined;
}
/**
* Adds a new element to the heap
*/
push(element) {
const i = this.stack.push(element);
this.heapU(i - 1);
}
areValid(...t) {
for (let i = 0; i < t.length; i++) {
if (t[i] < 0 || t[i] >= this.stack.length) {
return false;
}
}
return true;
}
heapD(i) {
const left = i * 2 + 1;
const right = i * 2 + 2;
let largest = i;
if (this.areValid(largest, left)) {
largest = this.gt(this.stack[left], this.stack[largest]) ? left : largest;
}
if (this.areValid(largest, right)) {
largest = this.gt(this.stack[right], this.stack[largest])
? right
: largest;
}
if (largest !== i) {
this.swap(largest, i);
this.heapD(largest);
}
}
heapU(i) {
const parent = i % 2 === 0 ? (i - 2) / 2 : (i - 1) / 2;
if (this.areValid(i, parent)) {
if (this.gt(this.stack[i], this.stack[parent])) {
this.swap(parent, i);
this.heapU(parent);
}
}
}
swap(a, b) {
if (this.areValid(a, b) && a !== b) {
;
[this.stack[a], this.stack[b]] = [this.stack[b], this.stack[a]];
}
}
}
exports.MaxHeap = MaxHeap;