@@ -28,63 +28,65 @@ export function pop(heap: Heap): Node | null {
2828 return null ;
2929 }
3030 const first = heap [ 0 ] ;
31-
3231 const last = heap . pop ( ) ;
33-
3432 if ( last !== first ) {
3533 heap [ 0 ] = last ;
3634 siftDown ( heap , last , 0 ) ;
3735 }
38-
3936 return first ;
4037}
4138
4239function siftUp ( heap , node , i ) {
4340 let index = i ;
44-
4541 while ( index > 0 ) {
4642 const parentIndex = ( index - 1 ) >>> 1 ;
4743 const parent = heap [ parentIndex ] ;
48-
49- if ( compare ( parent , node ) < 0 ) {
50- break ;
44+ if ( compare ( parent , node ) > 0 ) {
45+ // The parent is larger. Swap positions.
46+ heap [ parentIndex ] = node ;
47+ heap [ index ] = parent ;
48+ index = parentIndex ;
49+ } else {
50+ // The parent is smaller. Exit.
51+ return ;
5152 }
52- swap ( heap , parentIndex , index ) ;
53- index = parentIndex ;
5453 }
5554}
5655
5756function siftDown ( heap , node , i ) {
5857 let index = i ;
59- const halfLength = heap . length >>> 1 ;
60-
58+ const length = heap . length ;
59+ const halfLength = length >>> 1 ;
6160 while ( index < halfLength ) {
62- let bestIndex = index * 2 + 1 ;
63- const rightIndex = index * 2 + 2 ;
64-
65- // If the right node is smaller, swap with the smaller of those.
66- if (
67- heap . length > rightIndex &&
68- compare ( heap [ rightIndex ] , heap [ bestIndex ] ) < 0
69- ) {
70- bestIndex = rightIndex ;
71- }
72-
73- if ( compare ( node , heap [ bestIndex ] ) < 0 ) {
74- break ;
61+ const leftIndex = ( index + 1 ) * 2 - 1 ;
62+ const left = heap [ leftIndex ] ;
63+ const rightIndex = leftIndex + 1 ;
64+ const right = heap [ rightIndex ] ;
65+
66+ // If the left or right node is smaller, swap with the smaller of those.
67+ if ( compare ( left , node ) < 0 ) {
68+ if ( rightIndex < length && compare ( right , left ) < 0 ) {
69+ heap [ index ] = right ;
70+ heap [ rightIndex ] = node ;
71+ index = rightIndex ;
72+ } else {
73+ heap [ index ] = left ;
74+ heap [ leftIndex ] = node ;
75+ index = leftIndex ;
76+ }
77+ } else {
78+ if ( rightIndex < length && compare ( right , node ) < 0 ) {
79+ heap [ index ] = right ;
80+ heap [ rightIndex ] = node ;
81+ index = rightIndex ;
82+ } else {
83+ // Neither child is smaller. Exit.
84+ return ;
85+ }
7586 }
76-
77- swap ( heap , bestIndex , index ) ;
78- index = bestIndex ;
7987 }
8088}
8189
82- function swap ( heap , left , right ) {
83- const item = heap [ left ] ;
84- heap [ left ] = heap [ right ] ;
85- heap [ right ] = item ;
86- }
87-
8890function compare ( a , b ) {
8991 // Compare sort index first, then task id.
9092 const diff = a . sortIndex - b . sortIndex ;
0 commit comments