@utilityjs/min-heap
v2.0.0
Published
An implementation of MinHeap data structure.
Maintainers
Readme
UtilityJS | Min Heap
A min-heap data structure where the smallest element is at the root.
Features
- Min Heap Property: Smallest 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/min-heapor
pnpm add @utilityjs/min-heapUsage
Basic Usage
import { MinHeap } from "@utilityjs/min-heap";
const heap = new MinHeap<number>();
heap.add(5);
heap.add(3);
heap.add(7);
heap.add(1);
heap.peek(); // 1
heap.poll(); // 1
heap.poll(); // 3Custom Comparator
import { MinHeap } from "@utilityjs/min-heap";
interface Task {
name: string;
priority: number;
}
const heap = new MinHeap<Task>((a, b) => {
if (a.priority === b.priority) return 0;
return a.priority < b.priority ? -1 : 1;
});
heap.add({ name: "Low", priority: 3 });
heap.add({ name: "High", priority: 1 });
heap.add({ name: "Medium", priority: 2 });
heap.poll(); // { name: "High", priority: 1 }API
MinHeap<T>
Extends Heap<T>
Constructor
new MinHeap<T>(compareFunction?: CompareFunction<T>)- Creates a min-heap with optional comparator
Inherited Methods
isEmpty(): boolean- Check if the heap is emptypeek(): T | null- View the minimum element without removingpoll(): T | null- Remove and return the minimum 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.
