@utilityjs/heap
v2.0.0
Published
An implementation of abstract Heap class.
Maintainers
Readme
UtilityJS | Heap
An abstract heap data structure implementation.
Features
- Abstract Base Class: Extend to create min-heap or max-heap
- Custom Comparator: Support for custom element comparison
- Standard Operations: Add, poll, peek, remove, find
- Heapify Operations: Maintain heap property automatically
Installation
npm install @utilityjs/heapor
pnpm add @utilityjs/heapUsage
The Heap class is abstract and should be extended. See
@utilityjs/min-heap and
@utilityjs/max-heap for
concrete implementations.
Extending Heap
import { Heap } from "@utilityjs/heap";
class MinHeap<T> extends Heap<T> {
pairIsInCorrectOrder(first: T | null, second: T | null): boolean {
if (first == null || second == null) return false;
return this._comparator.isLessThanOrEqual(first, second);
}
}API
Heap<T>
Constructor
new Heap<T>(compareFunction?: CompareFunction<T>)- Creates a heap with optional comparator
Methods
isEmpty(): boolean- Check if the heap is emptypeek(): T | null- View the root element without removingpoll(): T | null- Remove and return the root 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
Index Methods
getLeftChildIndex(parentIndex): number- Get left child indexgetRightChildIndex(parentIndex): number- Get right child indexgetParentIndex(childIndex): number- Get parent indexhasParent(childIndex): boolean- Check if node has parenthasLeftChild(parentIndex): boolean- Check if node has left childhasRightChild(parentIndex): boolean- Check if node has right childgetLeftChild(parentIndex): T | null- Get left child elementgetRightChild(parentIndex): T | null- Get right child elementgetParent(childIndex): T | null- Get parent element
Heapify Methods
swap(index1, index2): void- Swap two elementsheapifyUp(startIndex?): void- Move element up to maintain heap propertyheapifyDown(startIndex?): void- Move element down to maintain heap property
Abstract Methods
pairIsInCorrectOrder(first: T | null, second: T | null): boolean- Define heap ordering
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.
