addressable-binary-heaps
Version:
A versatile TypeScript library for addressable binary heaps, delivering optimized and scalable min-heap and max-heap implementations, seamlessly supporting both object-oriented and functional paradigms.
85 lines (82 loc) • 2.58 kB
JavaScript
;
/**
* Clears the heap by removing all elements and their index mappings.
*
* @typeParam H - The type of heap array, must extend `IHeapArray`.
* @param instance - The heap instance to clear.
*/
function clear(instance) {
for (const node of instance) {
instance.indices.delete(node);
}
instance.length = 0;
}
/**
* Returns the current number of elements in the heap.
*
* @typeParam H - The type of heap array, must extend `IHeapArray`.
* @param instance - The heap instance to check.
* @returns The number of elements in the heap.
*/
function size(instance) {
return instance.length;
}
/**
* Returns the top element of heap without removing it.
* - For min-heaps, this is the minimum element.
* - For max-heaps, this is the maximum element.
*
* @typeParam H - The type of heap array, must extend `IHeapArray`.
* @param instance - The heap instance to peek.
* @returns The top element if heap is not empty, `undefined` otherwise.
*/
function peek(instance) {
return 0 === instance.length ? undefined : instance[0];
}
/**
* Generates an iterator that traverses the heap elements.
*
* *Note*: The traversal follows the order of the underlying array, not the priority order.
*
* @typeParam H - The type of heap array, must extend `IHeapArray`.
* @param instance - The heap instance to traverse.
* @param reversed - If `true`, the iterator will traverse the heap in reverse order.
* @returns A generator yielding heap elements in the specified order.
*/
function* entries(instance, reversed) {
if (reversed) {
for (let i = instance.length - 1; i >= 0; i -= 1) {
yield instance[i];
}
return;
}
for (const node of instance) {
yield node;
}
}
/**
* Generates an iterator that traverses the keys of heap elements.
*
* *Note*: The traversal follows the order of the underlying array, not the priority order.
*
* @typeParam H - The type of heap array, must extend `IHeapArray`.
* @param instance - The heap instance to traverse.
* @param reversed - If `true`, the iterator will traverse the heap in reverse order.
* @returns A generator yielding heap element keys in the specified order.
*/
function* keys(instance, reversed) {
if (reversed) {
for (let i = instance.length - 1; i >= 0; i -= 1) {
yield instance[i].key;
}
return;
}
for (const { key } of instance) {
yield key;
}
}
exports.clear = clear;
exports.entries = entries;
exports.keys = keys;
exports.peek = peek;
exports.size = size;