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
128
139module . exports = class PriorityQueue {
1410 #compare = ( a , b ) => a - b ;
15- #heap = new Array ( 64 ) ;
11+ #heap = [ undefined , undefined ] ;
1612 #setPosition;
1713 #size = 0 ;
1814
@@ -28,9 +24,6 @@ module.exports = class PriorityQueue {
2824const pos = ++ this . #size;
2925heap [ pos ] = value ;
3026
31- if ( heap . length === pos )
32- heap . length *= 2 ;
33-
3427this . percolateUp ( pos ) ;
3528}
3629
@@ -45,6 +38,7 @@ module.exports = class PriorityQueue {
4538percolateDown ( pos ) {
4639const compare = this . #compare;
4740const setPosition = this . #setPosition;
41+ const hasSetPosition = setPosition !== undefined ;
4842const heap = this . #heap;
4943const size = this . #size;
5044const hsize = size >> 1 ;
@@ -62,22 +56,23 @@ module.exports = class PriorityQueue {
6256
6357if ( compare ( item , childItem ) <= 0 ) break ;
6458
65- if ( setPosition !== undefined )
59+ if ( hasSetPosition )
6660setPosition ( childItem , pos ) ;
6761
6862heap [ pos ] = childItem ;
6963pos = child ;
7064}
7165
7266heap [ pos ] = item ;
73- if ( setPosition !== undefined )
67+ if ( hasSetPosition )
7468setPosition ( item , pos ) ;
7569}
7670
7771percolateUp ( pos ) {
7872const heap = this . #heap;
7973const compare = this . #compare;
8074const setPosition = this . #setPosition;
75+ const hasSetPosition = setPosition !== undefined ;
8176const item = heap [ pos ] ;
8277
8378while ( pos > 1 ) {
@@ -86,13 +81,13 @@ module.exports = class PriorityQueue {
8681if ( compare ( parentItem , item ) <= 0 )
8782break ;
8883heap [ pos ] = parentItem ;
89- if ( setPosition !== undefined )
84+ if ( hasSetPosition )
9085setPosition ( parentItem , pos ) ;
9186pos = parent ;
9287}
9388
9489heap [ pos ] = item ;
95- if ( setPosition !== undefined )
90+ if ( hasSetPosition )
9691setPosition ( item , pos ) ;
9792}
9893
0 commit comments