perf: improve code

This commit is contained in:
nomyfan 2021-05-22 15:08:04 +08:00
parent 6d2d8c9379
commit 8741b3a961
No known key found for this signature in database
GPG Key ID: 261D5F0C2ADD5A4F

View File

@ -148,14 +148,19 @@ export default class Heap {
* @return {Heap}
*/
remove(item, comparator = this.compare) {
// Find number of items to remove.
const numberOfItemsToRemove = this.find(item, comparator).length;
const findLastIndex = () => {
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) {
// 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();
return -1;
};
// 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.
// There is no need to heapify the heap afterwards.
if (indexToRemove === (this.heapContainer.length - 1)) {