@utilityjs/max-heap
v2.0.0
Published
An implementation of MaxHeap data structure.
Downloads
34
Maintainers
Readme
UtilityJS | Max Heap
A max-heap data structure where the largest element is at the root.
Features
- Max Heap Property: Largest element always at the root
- Custom Comparator: Support for custom element comparison
- Standard Operations: Add, poll, peek, remove, find
- Extends Heap: Built on the abstract Heap class
Installation
npm install @utilityjs/max-heapor
pnpm add @utilityjs/max-heapUsage
Basic Usage
import { MaxHeap } from "@utilityjs/max-heap";
const heap = new MaxHeap<number>();
heap.add(5);
heap.add(3);
heap.add(7);
heap.add(1);
heap.peek(); // 7
heap.poll(); // 7
heap.poll(); // 5Custom Comparator
import { MaxHeap } from "@utilityjs/max-heap";
interface Score {
player: string;
points: number;
}
const heap = new MaxHeap<Score>((a, b) => {
if (a.points === b.points) return 0;
return a.points < b.points ? -1 : 1;
});
heap.add({ player: "Alice", points: 100 });
heap.add({ player: "Bob", points: 150 });
heap.add({ player: "Charlie", points: 120 });
heap.poll(); // { player: "Bob", points: 150 }API
MaxHeap<T>
Extends Heap<T>
Constructor
new MaxHeap<T>(compareFunction?: CompareFunction<T>)- Creates a max-heap with optional comparator
Inherited Methods
isEmpty(): boolean- Check if the heap is emptypeek(): T | null- View the maximum element without removingpoll(): T | null- Remove and return the maximum elementadd(item: T): void- Add an element to the heapremove(item: T, comparator?): void- Remove all occurrences of an elementfind(item: T, comparator?): number[]- Find all indices of an elementtoString(): string- String representation of the heap
Contributing
Read the contributing guide to learn about our development process, how to propose bug fixes and improvements, and how to build and test your changes.
License
This project is licensed under the terms of the MIT license.
