mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 23:21:18 +08:00
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:
parent
9f83862212
commit
38688f25c5
@ -141,8 +141,8 @@ export default class MinHeap {
|
|||||||
*/
|
*/
|
||||||
remove(item, customFindingComparator) {
|
remove(item, customFindingComparator) {
|
||||||
// Find number of items to remove.
|
// Find number of items to remove.
|
||||||
const numberOfItemsToRemove = this.find(item).length;
|
|
||||||
const customComparator = customFindingComparator || this.compare;
|
const customComparator = customFindingComparator || this.compare;
|
||||||
|
const numberOfItemsToRemove = this.find(item, customComparator).length;
|
||||||
|
|
||||||
for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) {
|
for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) {
|
||||||
// We need to find item index to remove each time after removal since
|
// We need to find item index to remove each time after removal since
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import MinHeap from '../MinHeap';
|
import MinHeap from '../MinHeap';
|
||||||
|
import Comparator from '../../../utils/comparator/Comparator';
|
||||||
|
|
||||||
describe('MinHeap', () => {
|
describe('MinHeap', () => {
|
||||||
it('should create an empty min heap', () => {
|
it('should create an empty min heap', () => {
|
||||||
@ -147,4 +148,25 @@ describe('MinHeap', () => {
|
|||||||
expect(minHeap.remove(3).toString()).toEqual('4');
|
expect(minHeap.remove(3).toString()).toEqual('4');
|
||||||
expect(minHeap.remove(4).toString()).toEqual('');
|
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');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user