* @param {*} item * @param {Comparator} [comparator] * @return {Heap}
(item, comparator = this.compare)
| 148 | * @return {Heap} |
| 149 | */ |
| 150 | remove(item, comparator = this.compare) { |
| 151 | // Find number of items to remove. |
| 152 | const numberOfItemsToRemove = this.find(item, comparator).length; |
| 153 | |
| 154 | for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) { |
| 155 | // We need to find item index to remove each time after removal since |
| 156 | // indices are being changed after each heapify process. |
| 157 | const indexToRemove = this.find(item, comparator).pop(); |
| 158 | |
| 159 | // If we need to remove last child in the heap then just remove it. |
| 160 | // There is no need to heapify the heap afterwards. |
| 161 | if (indexToRemove === (this.heapContainer.length - 1)) { |
| 162 | this.heapContainer.pop(); |
| 163 | } else { |
| 164 | // Move last element in heap to the vacant (removed) position. |
| 165 | this.heapContainer[indexToRemove] = this.heapContainer.pop(); |
| 166 | |
| 167 | // Get parent. |
| 168 | const parentItem = this.parent(indexToRemove); |
| 169 | |
| 170 | // If there is no parent or parent is in correct order with the node |
| 171 | // we're going to delete then heapify down. Otherwise heapify up. |
| 172 | if ( |
| 173 | this.hasLeftChild(indexToRemove) |
| 174 | && ( |
| 175 | !parentItem |
| 176 | || this.pairIsInCorrectOrder(parentItem, this.heapContainer[indexToRemove]) |
| 177 | ) |
| 178 | ) { |
| 179 | this.heapifyDown(indexToRemove); |
| 180 | } else { |
| 181 | this.heapifyUp(indexToRemove); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | return this; |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * @param {*} item |
no test coverage detected