Skip to content

Commit c495e1f

Browse files
gurgundaytargos
authored andcommitted
lib: optimize priority queue
PR-URL: #60039 Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 9db54ad commit c495e1f

1 file changed

Lines changed: 7 additions & 12 deletions

File tree

‎lib/internal/priority_queue.js‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
'use strict';
22

3-
const{
4-
Array,
5-
}=primordials;
6-
73
// The PriorityQueue is a basic implementation of a binary heap that accepts
84
// a custom sorting function via its constructor. This function is passed
95
// the two nodes to compare, similar to the native Array#sort. Crucially
@@ -12,7 +8,7 @@ const {
128

139
module.exports=classPriorityQueue{
1410
#compare =(a,b)=>a-b;
15-
#heap =newArray(64);
11+
#heap =[undefined,undefined];
1612
#setPosition;
1713
#size =0;
1814

@@ -28,9 +24,6 @@ module.exports = class PriorityQueue {
2824
constpos=++this.#size;
2925
heap[pos]=value;
3026

31-
if(heap.length===pos)
32-
heap.length*=2;
33-
3427
this.percolateUp(pos);
3528
}
3629

@@ -45,6 +38,7 @@ module.exports = class PriorityQueue {
4538
percolateDown(pos){
4639
constcompare=this.#compare;
4740
constsetPosition=this.#setPosition;
41+
consthasSetPosition=setPosition!==undefined;
4842
constheap=this.#heap;
4943
constsize=this.#size;
5044
consthsize=size>>1;
@@ -62,22 +56,23 @@ module.exports = class PriorityQueue {
6256

6357
if(compare(item,childItem)<=0)break;
6458

65-
if(setPosition!==undefined)
59+
if(hasSetPosition)
6660
setPosition(childItem,pos);
6761

6862
heap[pos]=childItem;
6963
pos=child;
7064
}
7165

7266
heap[pos]=item;
73-
if(setPosition!==undefined)
67+
if(hasSetPosition)
7468
setPosition(item,pos);
7569
}
7670

7771
percolateUp(pos){
7872
constheap=this.#heap;
7973
constcompare=this.#compare;
8074
constsetPosition=this.#setPosition;
75+
consthasSetPosition=setPosition!==undefined;
8176
constitem=heap[pos];
8277

8378
while(pos>1){
@@ -86,13 +81,13 @@ module.exports = class PriorityQueue {
8681
if(compare(parentItem,item)<=0)
8782
break;
8883
heap[pos]=parentItem;
89-
if(setPosition!==undefined)
84+
if(hasSetPosition)
9085
setPosition(parentItem,pos);
9186
pos=parent;
9287
}
9388

9489
heap[pos]=item;
95-
if(setPosition!==undefined)
90+
if(hasSetPosition)
9691
setPosition(item,pos);
9792
}
9893

0 commit comments

Comments
 (0)