heap-js icon indicating copy to clipboard operation
heap-js copied to clipboard

Improve or supplement `contains` and `remove` functions

Open CarlOlson opened this issue 2 months ago • 1 comments

heap-js does not provide a good way to check if a heap contains a matching value or remove a matching value. contains, remove, indexOf, and indexOfEvery all take a value and IsEqual function. However, they also utilize this.compare as an optimization to not check all values. This severely limits the usefulness of these functions because you are required to retain references to the inserted objects. It can also cause unexpected errors.

Here is a little script that shows some behavior because of this.compare:

const HeapJs = require('heap-js').Heap;

const heap = new HeapJs((a, b) => b.value - a.value);

heap.add({ value: 1 });
heap.add({ value: 2 });
heap.add({ value: 3 });

console.log(heap.toArray());
// [ { value: 3 }, { value: 1 }, { value: 2 } ]

console.log(heap.remove({ value: 2 }));
// false (expected, different object)

console.log(heap.remove(0, (a, _) => a.value === 2));
// false (unexpected)

console.log(heap.remove(0, (a, _) => a.value === 3));
// true (unexpected given the previous result)

heap.remove(null);
// error (undesirable)

contains / indexOf / indexOfEvery https://github.com/ignlg/heap-js/blob/41206f64eea8c771fb58c93b3c151e6ba627619b/src/Heap.ts#L455-L459

remove https://github.com/ignlg/heap-js/blob/41206f64eea8c771fb58c93b3c151e6ba627619b/src/Heap.ts#L624-L638

CarlOlson avatar Oct 07 '25 01:10 CarlOlson

Indeed, there is an unexpected behavior here. This must be a TDD with your example as the test itself.

Thanks for your feedback @CarlOlson.

Willing to provide a PR draft?

ignlg avatar Oct 07 '25 09:10 ignlg