mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
perf: improve code
This commit is contained in:
parent
6d2d8c9379
commit
8741b3a961
@ -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)) {
|
||||||
|
Loading…
Reference in New Issue
Block a user