@@ -155,31 +155,40 @@ export default class Heap {
155
155
// We need to find item index to remove each time after removal since
156
156
// indices are being changed after each heapify process.
157
157
const indexToRemove = this . find ( item , comparator ) . pop ( ) ;
158
+ this . removeIndex ( indexToRemove ) ;
159
+ }
160
+
161
+ return this ;
162
+ }
158
163
159
- // If we need to remove last child in the heap then just remove it.
160
- // There is no need to heapify the heap afterwards.
161
- if ( indexToRemove === ( this . heapContainer . length - 1 ) ) {
162
- this . heapContainer . pop ( ) ;
164
+ /**
165
+ * @param {number } indexToRemove
166
+ * @return {Heap }
167
+ */
168
+ removeIndex ( indexToRemove ) {
169
+ // If we need to remove last child in the heap then just remove it.
170
+ // There is no need to heapify the heap afterwards.
171
+ if ( indexToRemove === ( this . heapContainer . length - 1 ) ) {
172
+ this . heapContainer . pop ( ) ;
173
+ } else {
174
+ // Move last element in heap to the vacant (removed) position.
175
+ this . heapContainer [ indexToRemove ] = this . heapContainer . pop ( ) ;
176
+
177
+ // Get parent.
178
+ const parentItem = this . parent ( indexToRemove ) ;
179
+
180
+ // If there is no parent or parent is in correct order with the node
181
+ // we're going to delete then heapify down. Otherwise heapify up.
182
+ if (
183
+ this . hasLeftChild ( indexToRemove )
184
+ && (
185
+ ! parentItem
186
+ || this . pairIsInCorrectOrder ( parentItem , this . heapContainer [ indexToRemove ] )
187
+ )
188
+ ) {
189
+ this . heapifyDown ( indexToRemove ) ;
163
190
} else {
164
- // Move last element in heap to the vacant (removed) position.
165
- this . heapContainer [ indexToRemove ] = this . heapContainer . pop ( ) ;
166
-
167
- // Get parent.
168
- const parentItem = this . parent ( indexToRemove ) ;
169
-
170
- // If there is no parent or parent is in correct order with the node
171
- // we're going to delete then heapify down. Otherwise heapify up.
172
- if (
173
- this . hasLeftChild ( indexToRemove )
174
- && (
175
- ! parentItem
176
- || this . pairIsInCorrectOrder ( parentItem , this . heapContainer [ indexToRemove ] )
177
- )
178
- ) {
179
- this . heapifyDown ( indexToRemove ) ;
180
- } else {
181
- this . heapifyUp ( indexToRemove ) ;
182
- }
191
+ this . heapifyUp ( indexToRemove ) ;
183
192
}
184
193
}
185
194
@@ -203,6 +212,15 @@ export default class Heap {
203
212
return foundItemIndices ;
204
213
}
205
214
215
+ /**
216
+ *
217
+ * @param {number } index
218
+ * @return {* }
219
+ */
220
+ getElementAtIndex ( index ) {
221
+ return this . heapContainer [ index ] ;
222
+ }
223
+
206
224
/**
207
225
* @return {boolean }
208
226
*/
0 commit comments