UNPKG

@figliolia/data-structures

Version:

Efficient data structures for every day programming

40 lines (39 loc) 1.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MinHeap = void 0; const Heap_1 = require("./Heap"); /** * Min Heap * * A heap that remains sorted ascendingly * * ```typescript * import { MinHeap } from "@figliolia/data-structures"; * * const heap = new MinHeap<number>(value => value); * heap.push(1); * heap.push(2); * heap.push(3); * heap.pop() // 1 * * const complexHeap = new MinHeap<{ id: number, name: string }>( * value => value.id // numeric value extractor * ); * complexHeap.push({ id: 1, name: "Jeff" }); * complexHeap.push({ id: 2, name: "Steve" }); * complexHeap.push({ id: 3, name: "Dave" }); * complexHeap.pop() // { id: 1, name: "Jeff" } * ``` */ class MinHeap extends Heap_1.Heap { nextChild(left, right) { return right < this.length && this.extract(this.storage[right]) < this.extract(this.storage[left]) ? right : left; } comparer(index1, index2) { return (this.extract(this.storage[index1]) >= this.extract(this.storage[index2])); } } exports.MinHeap = MinHeap;