Skip to content

Commit 38688f2

Browse files
m-maksyutintrekhleb
authored andcommitted
Fix the remove method for the MinHeap (trekhleb#50)
* Fix LinkedList * Fix the prepend method for the LinkedList * Fix the remove method for the MinHeap
1 parent 9f83862 commit 38688f2

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/data-structures/heap/MinHeap.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,8 @@ export default class MinHeap {
141141
*/
142142
remove(item, customFindingComparator) {
143143
// Find number of items to remove.
144-
const numberOfItemsToRemove = this.find(item).length;
145144
const customComparator = customFindingComparator || this.compare;
145+
const numberOfItemsToRemove = this.find(item, customComparator).length;
146146

147147
for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) {
148148
// We need to find item index to remove each time after removal since

src/data-structures/heap/__test__/MinHeap.test.js

+22
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import MinHeap from '../MinHeap';
2+
import Comparator from '../../../utils/comparator/Comparator';
23

34
describe('MinHeap', () => {
45
it('should create an empty min heap', () => {
@@ -147,4 +148,25 @@ describe('MinHeap', () => {
147148
expect(minHeap.remove(3).toString()).toEqual('4');
148149
expect(minHeap.remove(4).toString()).toEqual('');
149150
});
151+
152+
it('should be possible to remove items from heap with custom finding comparator', () => {
153+
const minHeap = new MinHeap();
154+
minHeap.add('dddd');
155+
minHeap.add('ccc');
156+
minHeap.add('bb');
157+
minHeap.add('a');
158+
159+
expect(minHeap.toString()).toBe('a,bb,ccc,dddd');
160+
161+
const comparator = new Comparator((a, b) => {
162+
if (a.length === b.length) {
163+
return 0;
164+
}
165+
166+
return a.length < b.length ? -1 : 1;
167+
});
168+
169+
minHeap.remove('hey', comparator);
170+
expect(minHeap.toString()).toBe('a,bb,dddd');
171+
});
150172
});

0 commit comments

Comments
 (0)