* BinaryHeap class represents a binary heap data structure that can be configured as a Min Heap or Max Heap. * * Binary heaps are binary trees that are filled level by level and from left to right inside each level. * They have the property that any parent node has a smaller (for Min Heap) or gre
| 6 | * than its children, ensuring that the root of the tree always holds the extremal value. |
| 7 | */ |
| 8 | class BinaryHeap { |
| 9 | /** |
| 10 | * Creates a new BinaryHeap instance. |
| 11 | * @constructor |
| 12 | * @param {Function} comparatorFunction - The comparator function used to determine the order of elements (e.g., minHeapComparator or maxHeapComparator). |
| 13 | */ |
| 14 | constructor(comparatorFunction) { |
| 15 | /** |
| 16 | * The heap array that stores elements. |
| 17 | * @member {Array} |
| 18 | */ |
| 19 | this.heap = [] |
| 20 | |
| 21 | /** |
| 22 | * The comparator function used for ordering elements in the heap. |
| 23 | * @member {Function} |
| 24 | */ |
| 25 | this.comparator = comparatorFunction |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Inserts a new value into the heap. |
| 30 | * @param {*} value - The value to be inserted into the heap. |
| 31 | */ |
| 32 | insert(value) { |
| 33 | this.heap.push(value) |
| 34 | this.#bubbleUp(this.heap.length - 1) |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Returns the number of elements in the heap. |
| 39 | * @returns {number} - The number of elements in the heap. |
| 40 | */ |
| 41 | size() { |
| 42 | return this.heap.length |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Checks if the heap is empty. |
| 47 | * @returns {boolean} - True if the heap is empty, false otherwise. |
| 48 | */ |
| 49 | empty() { |
| 50 | return this.size() === 0 |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Bubbles up a value from the specified index to maintain the heap property. |
| 55 | * @param {number} currIdx - The index of the value to be bubbled up. |
| 56 | * @private |
| 57 | */ |
| 58 | #bubbleUp(currIdx) { |
| 59 | let parentIdx = Math.floor((currIdx - 1) / 2) |
| 60 | |
| 61 | while ( |
| 62 | currIdx > 0 && |
| 63 | this.comparator(this.heap[currIdx], this.heap[parentIdx]) |
| 64 | ) { |
| 65 | this.#swap(currIdx, parentIdx) |
nothing calls this directly
no outgoing calls
no test coverage detected