This commit is contained in:
Kim Chan 2024-07-17 10:40:38 +09:00 committed by GitHub
commit 333bdde28a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -148,14 +148,19 @@ export default class Heap {
* @return {Heap} * @return {Heap}
*/ */
remove(item, comparator = this.compare) { remove(item, comparator = this.compare) {
// Find number of items to remove. const findLastIndex = () => {
const numberOfItemsToRemove = this.find(item, comparator).length; for (let index = this.heapContainer.length - 1; index >= 0; index -= 1) {
if (comparator.equal(item, this.heapContainer[index])) {
return index;
}
}
for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) { return -1;
// We need to find item index to remove each time after removal since };
// indices are being changed after each heapify process.
const indexToRemove = this.find(item, comparator).pop();
// We need to find item index to remove each time after removal since
// indices are being changed after each heapify process.
for (let indexToRemove = findLastIndex(); indexToRemove >= 0; indexToRemove = findLastIndex()) {
// If we need to remove last child in the heap then just remove it. // If we need to remove last child in the heap then just remove it.
// There is no need to heapify the heap afterwards. // There is no need to heapify the heap afterwards.
if (indexToRemove === (this.heapContainer.length - 1)) { if (indexToRemove === (this.heapContainer.length - 1)) {