1+ import Comparator from '../../utils/comparator/Comparator' ;
2+
13export default class MinHeap {
24 constructor ( ) {
35 // Array representation of the heap.
46 this . heapContainer = [ ] ;
7+ this . compare = new Comparator ( ) ;
58 }
69
710 static getLeftChildIndex ( parentIndex ) {
@@ -85,7 +88,7 @@ export default class MinHeap {
8588
8689 while (
8790 MinHeap . hasParent ( currentIndex ) &&
88- this . lessThen ( this . heapContainer [ currentIndex ] , this . parent ( currentIndex ) )
91+ this . compare . lessThen ( this . heapContainer [ currentIndex ] , this . parent ( currentIndex ) )
8992 ) {
9093 this . swap ( currentIndex , MinHeap . getParentIndex ( currentIndex ) ) ;
9194 currentIndex = MinHeap . getParentIndex ( currentIndex ) ;
@@ -101,14 +104,14 @@ export default class MinHeap {
101104 while ( this . hasLeftChild ( currentIndex ) ) {
102105 if (
103106 this . hasRightChild ( currentIndex ) &&
104- this . lessThen ( this . rightChild ( currentIndex ) , this . leftChild ( currentIndex ) )
107+ this . compare . lessThen ( this . rightChild ( currentIndex ) , this . leftChild ( currentIndex ) )
105108 ) {
106109 nextIndex = MinHeap . getRightChildIndex ( currentIndex ) ;
107110 } else {
108111 nextIndex = MinHeap . getLeftChildIndex ( currentIndex ) ;
109112 }
110113
111- if ( this . lessThen ( this . heapContainer [ currentIndex ] , this . heapContainer [ nextIndex ] ) ) {
114+ if ( this . compare . lessThen ( this . heapContainer [ currentIndex ] , this . heapContainer [ nextIndex ] ) ) {
112115 break ;
113116 }
114117
@@ -120,18 +123,4 @@ export default class MinHeap {
120123 toString ( ) {
121124 return this . heapContainer . toString ( ) ;
122125 }
123-
124- compare ( a , b ) {
125- if ( a === b ) {
126- return 0 ;
127- }
128-
129- // Min heap may be converted to max heap by simply changing this line to:
130- // a > b ? -1 : 1
131- return a < b ? - 1 : 1 ;
132- }
133-
134- lessThen ( a , b ) {
135- return this . compare ( a , b ) === - 1 ;
136- }
137126}
0 commit comments