UNPKG

@figliolia/data-structures

Version:

Efficient data structures for every day programming

69 lines (68 loc) 1.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Heap = void 0; /** * Heap * * The base construct of the MinHeap and MaxHeap utilities */ class Heap { constructor(valueExtractor) { this.storage = []; 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); } } exports.Heap = Heap;