MCPcopy Index your code
hub / github.com/trekhleb/javascript-algorithms / remove

Method remove

src/data-structures/heap/Heap.js:150–187  ·  view source on GitHub ↗

* @param {*} item * @param {Comparator} [comparator] * @return {Heap}

(item, comparator = this.compare)

Source from the content-addressed store, hash-verified

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

Callers 2

MinHeap.test.jsFile · 0.45
MaxHeap.test.jsFile · 0.45

Calls 7

findMethod · 0.95
parentMethod · 0.95
hasLeftChildMethod · 0.95
pairIsInCorrectOrderMethod · 0.95
heapifyDownMethod · 0.95
heapifyUpMethod · 0.95
popMethod · 0.80

Tested by

no test coverage detected