Fix the remove method for the MinHeap (#50)

* Fix LinkedList

* Fix the prepend method for the LinkedList

* Fix the remove method for the MinHeap
This commit is contained in:
m-maksyutin 2018-06-05 16:17:14 +03:00 committed by Oleksii Trekhleb
parent 9f83862212
commit 38688f25c5
2 changed files with 23 additions and 1 deletions

View File

@ -141,8 +141,8 @@ export default class MinHeap {
*/
remove(item, customFindingComparator) {
// Find number of items to remove.
const numberOfItemsToRemove = this.find(item).length;
const customComparator = customFindingComparator || this.compare;
const numberOfItemsToRemove = this.find(item, customComparator).length;
for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) {
// We need to find item index to remove each time after removal since

View File

@ -1,4 +1,5 @@
import MinHeap from '../MinHeap';
import Comparator from '../../../utils/comparator/Comparator';
describe('MinHeap', () => {
it('should create an empty min heap', () => {
@ -147,4 +148,25 @@ describe('MinHeap', () => {
expect(minHeap.remove(3).toString()).toEqual('4');
expect(minHeap.remove(4).toString()).toEqual('');
});
it('should be possible to remove items from heap with custom finding comparator', () => {
const minHeap = new MinHeap();
minHeap.add('dddd');
minHeap.add('ccc');
minHeap.add('bb');
minHeap.add('a');
expect(minHeap.toString()).toBe('a,bb,ccc,dddd');
const comparator = new Comparator((a, b) => {
if (a.length === b.length) {
return 0;
}
return a.length < b.length ? -1 : 1;
});
minHeap.remove('hey', comparator);
expect(minHeap.toString()).toBe('a,bb,dddd');
});
});