UNPKG

@datastructures-js/heap

Version:

Min/Max Heap & Heap Sort implementation in javascript

97 lines (86 loc) 2.04 kB
/** * @license MIT * @copyright 2020 Eyas Ranjous <eyas.ranjous@gmail.com> */ const { Heap } = require('./heap'); const getMaxCompare = (getCompareValue) => (a, b) => { const aVal = typeof getCompareValue === 'function' ? getCompareValue(a) : a; const bVal = typeof getCompareValue === 'function' ? getCompareValue(b) : b; return aVal < bVal ? 1 : -1; }; /** * @class MaxHeap * @extends Heap */ class MaxHeap extends Heap { /** * @param {function} [getCompareValue] * @param {array} [values] */ constructor(getCompareValue, values) { super(getMaxCompare(getCompareValue), values); this._getCompareValue = getCompareValue; } /** * Inserts a new value into the heap * @public * @param {number|string|object} value * @returns {MaxHeap} */ insert(value) { super.insert(value); return this; } /** * Inserts a new value into the heap * @public * @param {number|string|object} value * @returns {MaxHeap} */ push(value) { return this.insert(value); } /** * Fixes node positions in the heap * @public * @returns {MaxHeap} */ fix() { super.fix(); return this; } /** * Returns a shallow copy of the MaxHeap * @public * @returns {MaxHeap} */ clone() { return new MaxHeap(this._getCompareValue, this._nodes.slice()); } /** * Builds a MaxHeap from an array * @public * @static * @param {array} values * @param {function} [getCompareValue] * @returns {MaxHeap} */ static heapify(values, getCompareValue) { if (!Array.isArray(values)) { throw new Error('MaxHeap.heapify expects an array'); } return new MaxHeap(getCompareValue, values); } /** * Checks if a list of values is a valid max heap * @public * @static * @param {array} values * @param {function} [getCompareValue] * @returns {boolean} */ static isHeapified(values, getCompareValue) { return new MaxHeap(getCompareValue, values).isValid(); } } exports.MaxHeap = MaxHeap;