UNPKG

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.

77 lines (75 loc) 2.48 kB
/** * 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) { instance.forEach((node) => 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; } } export { clear, entries, keys, peek, size };