0.1.0 • Published 12 months ago
@caelus-dts/heap v0.1.0
@caelus-dts/queue
Overview
A TypeScript implementation of a heap data structure, a specialized tree-based structure that satisfies the heap property.
- Heap Property: The element with the highest priority (determined by a comparison function) is always at the root of the heap.
Installation
- using
npm
npm install @caelus-dts/heap- using
yarn
yarn add @caelus-dts/heap- using
pnpm
pnpm add @caelus-dts/heapUsage
import Heap from '@caelus-dts/heap';
// Comparison function for numbers (min-heap)
const compareNumbers = (a, b) => a - b;
// Create a new min-heap of numbers
const minHeap = new Heap(compareNumbers);
// Add some numbers
minHeap.add(5);
minHeap.add(2);
minHeap.add(8);
minHeap.add(1);
// Peek at the smallest element (should be 1)
console.log(minHeap.peek()); // Output: 1
// Remove the smallest element
console.log(minHeap.remove()); // Output: 1
// Convert to array
console.log(minHeap.toArray()); // Output: [2, 5, 8]
// Example with string values and different compare function
const compareLength = (a, b) => a.length - b.length;
const heapStrings = new Heap<string>(compareLength)
heapStrings.add('short')
heapStrings.add('longer')
heapStrings.add('a');
console.log(heapStrings.peek()); // 'a'API Documentation
Constructor
new Heap<T>(compareFunc: HeapCompareFunc<T>)
Creates a new Heap instance.
compareFunc: The function used to compare elements in the heap, determining their priority.
Properties
isEmpty: Returnstrueif the heap is empty,falseotherwise.size: Returns the number of elements in the heap.
Methods
add(item: T): Adds a new element to the heap.clear(): Removes all elements from the heap.peek(): Returns the root element of the heap (element with highest priority) without removing it. Returnsundefinedif the heap is empty.remove(): Removes and returns the root element of the heap. Returnsundefinedif the heap is empty.toArray(): Returns a shallow copy of the heap's elements as an array.
Contributing
Contributions are welcome! Please fork the repository and submit a pull request.
License
0.1.0
12 months ago