priority-queue-typed 2.4.2 → 2.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +1 -7
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs-legacy/index.cjs +1 -7
- package/dist/cjs-legacy/index.cjs.map +1 -1
- package/dist/esm/index.mjs +1 -7
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm-legacy/index.mjs +1 -7
- package/dist/esm-legacy/index.mjs.map +1 -1
- package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
- package/dist/types/data-structures/binary-tree/binary-tree.d.ts +5 -5
- package/dist/types/data-structures/binary-tree/bst.d.ts +1 -1
- package/dist/types/data-structures/binary-tree/tree-map.d.ts +10 -0
- package/dist/types/data-structures/binary-tree/tree-set.d.ts +10 -0
- package/dist/types/data-structures/graph/directed-graph.d.ts +2 -2
- package/dist/types/data-structures/graph/undirected-graph.d.ts +2 -2
- package/dist/types/data-structures/hash/hash-map.d.ts +2 -2
- package/dist/types/data-structures/heap/heap.d.ts +3 -7
- package/dist/types/types/data-structures/binary-tree/avl-tree.d.ts +1 -1
- package/dist/types/types/data-structures/binary-tree/red-black-tree.d.ts +1 -1
- package/dist/types/types/data-structures/linked-list/doubly-linked-list.d.ts +1 -1
- package/dist/types/types/data-structures/linked-list/singly-linked-list.d.ts +1 -1
- package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +1 -1
- package/dist/types/types/data-structures/stack/stack.d.ts +1 -1
- package/dist/umd/priority-queue-typed.js +1 -7
- package/dist/umd/priority-queue-typed.js.map +1 -1
- package/dist/umd/priority-queue-typed.min.js +1 -1
- package/dist/umd/priority-queue-typed.min.js.map +1 -1
- package/package.json +2 -2
- package/src/data-structures/base/iterable-element-base.ts +2 -2
- package/src/data-structures/binary-tree/binary-tree.ts +8 -7
- package/src/data-structures/binary-tree/bst.ts +1 -1
- package/src/data-structures/binary-tree/tree-map.ts +16 -0
- package/src/data-structures/binary-tree/tree-multi-set.ts +5 -5
- package/src/data-structures/binary-tree/tree-set.ts +16 -0
- package/src/data-structures/graph/abstract-graph.ts +18 -18
- package/src/data-structures/graph/directed-graph.ts +4 -4
- package/src/data-structures/graph/map-graph.ts +1 -1
- package/src/data-structures/graph/undirected-graph.ts +4 -4
- package/src/data-structures/hash/hash-map.ts +6 -4
- package/src/data-structures/heap/heap.ts +17 -14
- package/src/data-structures/linked-list/doubly-linked-list.ts +4 -4
- package/src/data-structures/linked-list/singly-linked-list.ts +15 -9
- package/src/data-structures/queue/deque.ts +1 -1
- package/src/data-structures/stack/stack.ts +1 -1
- package/src/data-structures/trie/trie.ts +10 -5
- package/src/types/data-structures/binary-tree/avl-tree.ts +1 -1
- package/src/types/data-structures/binary-tree/red-black-tree.ts +1 -1
- package/src/types/data-structures/linked-list/doubly-linked-list.ts +1 -1
- package/src/types/data-structures/linked-list/singly-linked-list.ts +1 -1
- package/src/types/data-structures/priority-queue/priority-queue.ts +1 -1
- package/src/types/data-structures/stack/stack.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/heap/heap.ts","../../src/data-structures/heap/max-heap.ts","../../src/data-structures/heap/min-heap.ts","../../src/data-structures/priority-queue/priority-queue.ts","../../src/data-structures/priority-queue/min-priority-queue.ts","../../src/data-structures/priority-queue/max-priority-queue.ts","../../src/common/index.ts"],"sourcesContent":["/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nexport * from './data-structures/priority-queue';\nexport * from './data-structures/heap';\nexport * from './types/data-structures/priority-queue';\nexport * from './types/data-structures/heap';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: Each node in a heap follows a specific order property, which varies depending on the type of heap:\n * Max Heap: The value of each parent node is greater than or equal to the value of its children.\n * Min Heap: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n * // basic Heap creation and add operation\n * // Create a min heap (default)\n * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);\n *\n * // Verify size\n * console.log(minHeap.size); // 6;\n *\n * // Add new element\n * minHeap.add(4);\n * console.log(minHeap.size); // 7;\n *\n * // Min heap property: smallest element at root\n * const min = minHeap.peek();\n * console.log(min); // 1;\n * @example\n * // Heap with custom comparator (MaxHeap behavior)\n * interface Task {\n * id: number;\n * priority: number;\n * name: string;\n * }\n *\n * // Custom comparator for max heap behavior (higher priority first)\n * const tasks: Task[] = [\n * { id: 1, priority: 5, name: 'Email' },\n * { id: 2, priority: 3, name: 'Chat' },\n * { id: 3, priority: 8, name: 'Alert' }\n * ];\n *\n * const maxHeap = new Heap(tasks, {\n * comparator: (a: Task, b: Task) => b.priority - a.priority\n * });\n *\n * console.log(maxHeap.size); // 3;\n *\n * // Peek returns highest priority task\n * const topTask = maxHeap.peek();\n * console.log(topTask?.priority); // 8;\n * console.log(topTask?.name); // 'Alert';\n * @example\n * // Heap for event processing with priority\n * interface Event {\n * id: number;\n * type: 'critical' | 'warning' | 'info';\n * timestamp: number;\n * message: string;\n * }\n *\n * // Custom priority: critical > warning > info\n * const priorityMap = { critical: 3, warning: 2, info: 1 };\n *\n * const eventHeap = new Heap<Event>([], {\n * comparator: (a: Event, b: Event) => {\n * const priorityA = priorityMap[a.type];\n * const priorityB = priorityMap[b.type];\n * return priorityB - priorityA; // Higher priority first\n * }\n * });\n *\n * // Add events in random order\n * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });\n * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });\n * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });\n * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });\n * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });\n *\n * console.log(eventHeap.size); // 5;\n *\n * // Process events by priority (critical first)\n * const processedOrder: Event[] = [];\n * while (eventHeap.size > 0) {\n * const event = eventHeap.poll();\n * if (event) {\n * processedOrder.push(event);\n * }\n * }\n *\n * // Verify critical events came first\n * console.log(processedOrder[0].type); // 'critical';\n * console.log(processedOrder[1].type); // 'critical';\n * console.log(processedOrder[2].type); // 'warning';\n * console.log(processedOrder[3].type); // 'info';\n * console.log(processedOrder[4].type); // 'info';\n *\n * // Verify O(log n) operations\n * const newHeap = new Heap<number>([5, 3, 7, 1]);\n *\n * // Add - O(log n)\n * newHeap.add(2);\n * console.log(newHeap.size); // 5;\n *\n * // Poll - O(log n)\n * const removed = newHeap.poll();\n * console.log(removed); // 1;\n *\n * // Peek - O(1)\n * const top = newHeap.peek();\n * console.log(top); // 2;\n * @example\n * // Use Heap to solve top k problems\n * function topKElements(arr: number[], k: number): number[] {\n * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap\n * arr.forEach(num => {\n * heap.add(num);\n * if (heap.size > k) heap.poll(); // Keep the heap size at K\n * });\n * return heap.toArray();\n * }\n *\n * const numbers = [10, 30, 20, 5, 15, 25];\n * console.log(topKElements(numbers, 3)); // [15, 10, 5];\n * @example\n * // Use Heap to dynamically maintain the median\n * class MedianFinder {\n * private low: MaxHeap<number>; // Max heap, stores the smaller half\n * private high: MinHeap<number>; // Min heap, stores the larger half\n *\n * constructor() {\n * this.low = new MaxHeap<number>([]);\n * this.high = new MinHeap<number>([]);\n * }\n *\n * addNum(num: number): void {\n * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);\n * else this.high.add(num);\n *\n * // Balance heaps\n * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);\n * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);\n * }\n *\n * findMedian(): number {\n * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;\n * return this.low.peek()!;\n * }\n * }\n *\n * const medianFinder = new MedianFinder();\n * medianFinder.addNum(10);\n * console.log(medianFinder.findMedian()); // 10;\n * medianFinder.addNum(20);\n * console.log(medianFinder.findMedian()); // 15;\n * medianFinder.addNum(30);\n * console.log(medianFinder.findMedian()); // 20;\n * medianFinder.addNum(40);\n * console.log(medianFinder.findMedian()); // 25;\n * medianFinder.addNum(50);\n * console.log(medianFinder.findMedian()); // 30;\n * @example\n * // Use Heap for load balancing\n * function loadBalance(requests: number[], servers: number): number[] {\n * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap\n * const serverLoads = new Array(servers).fill(0);\n *\n * for (let i = 0; i < servers; i++) {\n * serverHeap.add({ id: i, load: 0 });\n * }\n *\n * requests.forEach(req => {\n * const server = serverHeap.poll()!;\n * serverLoads[server.id] += req;\n * server.load += req;\n * serverHeap.add(server); // The server after updating the load is re-entered into the heap\n * });\n *\n * return serverLoads;\n * }\n *\n * const requests = [5, 2, 8, 3, 7];\n * console.log(loadBalance(requests, 3)); // [12, 8, 5];\n * @example\n * // Use Heap to schedule tasks\n * type Task = [string, number];\n *\n * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {\n * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap\n * const allocation = new Map<number, Task[]>();\n *\n * // Initialize the load on each machine\n * for (let i = 0; i < machines; i++) {\n * machineHeap.add({ id: i, load: 0 });\n * allocation.set(i, []);\n * }\n *\n * // Assign tasks\n * tasks.forEach(([task, load]) => {\n * const machine = machineHeap.poll()!;\n * allocation.get(machine.id)!.push([task, load]);\n * machine.load += load;\n * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap\n * });\n *\n * return allocation;\n * }\n *\n * const tasks: Task[] = [\n * ['Task1', 3],\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task4', 5],\n * ['Task5', 4]\n * ];\n * const expectedMap = new Map<number, Task[]>();\n * expectedMap.set(0, [\n * ['Task1', 3],\n * ['Task4', 5]\n * ]);\n * expectedMap.set(1, [\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task5', 4]\n * ]);\n * console.log(scheduleTasks(tasks, 2)); // expectedMap;\n */\nexport class Heap<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is;\n\n /**\n * Create a Heap and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw values if toElementFn is set).\n * @param [options] - Options such as comparator and toElementFn.\n * @returns New Heap instance.\n */\n\n constructor(elements: Iterable<E | R> = [], options?: HeapOptions<E, R>) {\n super(options);\n\n if (options) {\n const { comparator } = options;\n if (comparator) this._comparator = comparator;\n }\n\n this.addMany(elements as Iterable<E | R>);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of the heap.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Heap size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Get the last leaf element.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get leaf(): E | undefined {\n return this.elements[this.size - 1] ?? undefined;\n }\n\n /**\n * Create a heap of the same class from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template R\n * @template S\n * @param [elements] - Iterable of elements or raw records.\n * @param [options] - Heap options including comparator.\n * @returns A new heap instance of this class.\n */\n\n static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(\n this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,\n elements?: Iterable<T | R>,\n options?: HeapOptions<T, R>\n ): S {\n return new this(elements, options);\n }\n\n /**\n * Build a Heap from an iterable in linear time given a comparator.\n * @remarks Time O(N), Space O(N)\n * @template EE\n * @template RR\n * @param elements - Iterable of elements.\n * @param options - Heap options including comparator.\n * @returns A new Heap built from elements.\n */\n\n static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {\n return new Heap<EE, RR>(elements, options);\n }\n\n /**\n * Insert an element.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns True.\n */\n\n add(element: E): boolean {\n this._elements.push(element);\n return this._bubbleUp(this.elements.length - 1);\n }\n\n /**\n * Insert many elements from an iterable.\n * @remarks Time O(N log N), Space O(1)\n * @param elements - Iterable of elements or raw values.\n * @returns Array of per-element success flags.\n */\n\n addMany(elements: Iterable<E | R>): boolean[] {\n const flags: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n const ok = this.add(this.toElementFn(el as R));\n flags.push(ok);\n } else {\n const ok = this.add(el as E);\n flags.push(ok);\n }\n }\n return flags;\n }\n\n /**\n * Remove and return the top element.\n * @remarks Time O(log N), Space O(1)\n * @returns Top element or undefined.\n */\n\n poll(): E | undefined {\n if (this.elements.length === 0) return;\n const value = this.elements[0];\n const last = this.elements.pop()!;\n if (this.elements.length) {\n this.elements[0] = last;\n this._sinkDown(0, this.elements.length >> 1);\n }\n return value;\n }\n\n /**\n * Get the current top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.elements[0];\n }\n\n /**\n * Check whether the heap is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Remove all elements.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Replace the backing array and rebuild the heap.\n * @remarks Time O(N), Space O(N)\n * @param elements - Iterable used to refill the heap.\n * @returns Array of per-node results from fixing steps.\n */\n\n refill(elements: Iterable<E>): boolean[] {\n this._elements = Array.from(elements);\n return this.fix();\n }\n\n /**\n * Check if an equal element exists in the heap.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to search for.\n * @returns True if found.\n */\n\n override has(element: E): boolean {\n for (const el of this.elements) if (this._equals(el, element)) return true;\n return false;\n }\n\n /**\n * Delete one occurrence of an element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to delete.\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n let index = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (this._equals(this.elements[i], element)) {\n index = i;\n break;\n }\n }\n if (index < 0) return false;\n if (index === 0) {\n this.poll();\n } else if (index === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(index, 1, this.elements.pop()!);\n this._bubbleUp(index);\n this._sinkDown(index, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Delete the first element that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (element, index, heap) → boolean.\n * @returns True if an element was removed.\n */\n\n deleteBy(predicate: (element: E, index: number, heap: this) => boolean): boolean {\n let idx = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n idx = i;\n break;\n }\n }\n if (idx < 0) return false;\n if (idx === 0) {\n this.poll();\n } else if (idx === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(idx, 1, this.elements.pop()!);\n this._bubbleUp(idx);\n this._sinkDown(idx, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Set the equality comparator used by has/delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This heap.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Traverse the binary heap as a complete binary tree and collect elements.\n * @remarks Time O(N), Space O(H)\n * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.\n * @returns Array of visited elements.\n */\n\n dfs(order: DFSOrderPattern = 'PRE'): E[] {\n const result: E[] = [];\n const _dfs = (index: number) => {\n const left = 2 * index + 1,\n right = left + 1;\n if (index < this.size) {\n if (order === 'IN') {\n _dfs(left);\n result.push(this.elements[index]);\n _dfs(right);\n } else if (order === 'PRE') {\n result.push(this.elements[index]);\n _dfs(left);\n _dfs(right);\n } else if (order === 'POST') {\n _dfs(left);\n _dfs(right);\n result.push(this.elements[index]);\n }\n }\n };\n _dfs(0);\n return result;\n }\n\n /**\n * Restore heap order bottom-up (heapify in-place).\n * @remarks Time O(N), Space O(1)\n * @returns Array of per-node results from fixing steps.\n */\n\n fix(): boolean[] {\n const results: boolean[] = [];\n for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {\n results.push(this._sinkDown(i, this.elements.length >> 1));\n }\n return results;\n }\n\n /**\n * Return all elements in ascending order by repeatedly polling.\n * @remarks Time O(N log N), Space O(N)\n * @returns Sorted array of elements.\n */\n\n sort(): E[] {\n const visited: E[] = [];\n const cloned = this._createInstance();\n for (const x of this.elements) cloned.add(x);\n while (!cloned.isEmpty()) {\n const top = cloned.poll();\n if (top !== undefined) visited.push(top);\n }\n return visited;\n }\n\n /**\n * Deep clone this heap.\n * @remarks Time O(N), Space O(N)\n * @returns A new heap with the same elements.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this.elements) next.add(x);\n return next;\n }\n\n /**\n * Filter elements into a new heap of the same class.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Predicate (element, index, heap) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with the kept elements.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n if (thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {\n out.add(x);\n } else {\n i++;\n }\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of possibly different element type.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, heap) → newElement.\n * @param options - Options for the output heap, including comparator for EM.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options: HeapOptions<EM, RM> & { comparator: Comparator<EM> },\n thisArg?: unknown\n ): Heap<EM, RM> {\n const { comparator, toElementFn, ...rest } = options ?? {};\n if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');\n const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of the same element type.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Mapping function (element, index, heap) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n protected _DEFAULT_COMPARATOR = (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError('When comparing object types, define a custom comparator in options.');\n }\n if ((a as unknown as number) > (b as unknown as number)) return 1;\n if ((a as unknown as number) < (b as unknown as number)) return -1;\n return 0;\n };\n\n protected _comparator: Comparator<E> = this._DEFAULT_COMPARATOR; /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n\n get comparator() {\n return this._comparator;\n }\n\n protected *_getIterator(): IterableIterator<E> {\n for (const element of this.elements) yield element;\n }\n\n protected _bubbleUp(index: number): boolean {\n const element = this.elements[index];\n while (index > 0) {\n const parent = (index - 1) >> 1;\n const parentItem = this.elements[parent];\n if (this.comparator(parentItem, element) <= 0) break;\n this.elements[index] = parentItem;\n index = parent;\n }\n this.elements[index] = element;\n return true;\n }\n\n protected _sinkDown(index: number, halfLength: number): boolean {\n const element = this.elements[index];\n while (index < halfLength) {\n let left = (index << 1) | 1;\n const right = left + 1;\n let minItem = this.elements[left];\n if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {\n left = right;\n minItem = this.elements[right];\n }\n if (this.comparator(minItem, element) >= 0) break;\n this.elements[index] = minItem;\n index = left;\n }\n this.elements[index] = element;\n return true;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options to override comparator or toElementFn.\n * @returns A like-kind empty heap instance.\n */\n\n protected _createInstance(options?: HeapOptions<E, R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...(options ?? {}) });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind instance seeded by elements.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable of elements or raw values to seed.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind heap instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: HeapOptions<EM, RM>\n ): Heap<EM, RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Heap<EM, RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind heap instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind heap instance.\n */\n\n protected _spawnLike<EM, RM>(options?: HeapOptions<EM, RM>): Heap<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\n/**\n * Node container used by FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class FibonacciHeapNode<E> {\n element: E;\n degree: number;\n left?: FibonacciHeapNode<E>;\n right?: FibonacciHeapNode<E>;\n child?: FibonacciHeapNode<E>;\n parent?: FibonacciHeapNode<E>;\n marked: boolean;\n\n constructor(element: E, degree = 0) {\n this.element = element;\n this.degree = degree;\n this.marked = false;\n }\n}\n\n/**\n * Fibonacci heap (min-heap) optimized for fast merges and amortized operations.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @example examples will be generated by unit test\n */\nexport class FibonacciHeap<E> {\n /**\n * Create a FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @param [comparator] - Comparator to order elements (min-heap by default).\n * @returns New FibonacciHeap instance.\n */\n\n constructor(comparator?: Comparator<E>) {\n this.clear();\n this._comparator = comparator || this._defaultComparator;\n if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');\n }\n\n protected _root?: FibonacciHeapNode<E>;\n\n /**\n * Get the circular root list head.\n * @remarks Time O(1), Space O(1)\n * @returns Root node or undefined.\n */\n\n get root(): FibonacciHeapNode<E> | undefined {\n return this._root;\n }\n\n protected _size = 0;\n get size(): number {\n return this._size;\n }\n\n protected _min?: FibonacciHeapNode<E>;\n\n /**\n * Get the current minimum node.\n * @remarks Time O(1), Space O(1)\n * @returns Min node or undefined.\n */\n\n get min(): FibonacciHeapNode<E> | undefined {\n return this._min;\n }\n\n protected _comparator: Comparator<E>;\n get comparator(): Comparator<E> {\n return this._comparator;\n }\n\n clear(): void {\n this._root = undefined;\n this._min = undefined;\n this._size = 0;\n }\n\n add(element: E): boolean {\n this.push(element);\n return true;\n }\n\n /**\n * Push an element into the root list.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns This heap.\n */\n\n push(element: E): this {\n const node = this.createNode(element);\n node.left = node;\n node.right = node;\n this.mergeWithRoot(node);\n if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;\n this._size++;\n return this;\n }\n\n peek(): E | undefined {\n return this.min ? this.min.element : undefined;\n }\n\n /**\n * Collect nodes from a circular doubly linked list starting at head.\n * @remarks Time O(K), Space O(K)\n * @param [head] - Start node of the circular list.\n * @returns Array of nodes from the list.\n */\n\n consumeLinkedList(head?: FibonacciHeapNode<E>): FibonacciHeapNode<E>[] {\n const elements: FibonacciHeapNode<E>[] = [];\n if (!head) return elements;\n let node: FibonacciHeapNode<E> | undefined = head;\n let started = false;\n while (true) {\n if (node === head && started) break;\n else if (node === head) started = true;\n elements.push(node!);\n node = node!.right;\n }\n return elements;\n }\n\n /**\n * Insert a node into a parent's child list (circular).\n * @remarks Time O(1), Space O(1)\n * @param parent - Parent node.\n * @param node - Child node to insert.\n * @returns void\n */\n\n mergeWithChild(parent: FibonacciHeapNode<E>, node: FibonacciHeapNode<E>): void {\n if (!parent.child) parent.child = node;\n else {\n node.right = parent.child.right;\n node.left = parent.child;\n parent.child.right!.left = node;\n parent.child.right = node;\n }\n }\n\n poll(): E | undefined {\n return this.pop();\n }\n\n /**\n * Remove and return the minimum element, consolidating the root list.\n * @remarks Time O(log N) amortized, Space O(1)\n * @returns Minimum element or undefined.\n */\n\n pop(): E | undefined {\n if (this._size === 0) return undefined;\n const z = this.min!;\n if (z.child) {\n const elements = this.consumeLinkedList(z.child);\n for (const node of elements) {\n this.mergeWithRoot(node);\n node.parent = undefined;\n }\n }\n this.removeFromRoot(z);\n if (z === z.right) {\n this._min = undefined;\n this._root = undefined;\n } else {\n this._min = z.right;\n this._consolidate();\n }\n this._size--;\n return z.element;\n }\n\n /**\n * Meld another heap into this heap.\n * @remarks Time O(1), Space O(1)\n * @param heapToMerge - Another FibonacciHeap to meld into this one.\n * @returns void\n */\n\n merge(heapToMerge: FibonacciHeap<E>): void {\n if (heapToMerge.size === 0) return;\n if (this.root && heapToMerge.root) {\n const thisRoot = this.root,\n otherRoot = heapToMerge.root;\n const thisRootRight = thisRoot.right!,\n otherRootLeft = otherRoot.left!;\n thisRoot.right = otherRoot;\n otherRoot.left = thisRoot;\n thisRootRight.left = otherRootLeft;\n otherRootLeft.right = thisRootRight;\n } else if (!this.root && heapToMerge.root) {\n this._root = heapToMerge.root;\n }\n if (!this.min || (heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0)) {\n this._min = heapToMerge.min;\n }\n this._size += heapToMerge.size;\n heapToMerge.clear();\n }\n\n createNode(element: E): FibonacciHeapNode<E> {\n return new FibonacciHeapNode<E>(element);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n protected _defaultComparator(a: E, b: E): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n protected mergeWithRoot(node: FibonacciHeapNode<E>): void {\n if (!this.root) this._root = node;\n else {\n node.right = this.root.right;\n node.left = this.root;\n this.root.right!.left = node;\n this.root.right = node;\n }\n }\n\n protected removeFromRoot(node: FibonacciHeapNode<E>): void {\n if (this.root === node) this._root = node.right;\n if (node.left) node.left.right = node.right;\n if (node.right) node.right.left = node.left;\n }\n\n protected _link(y: FibonacciHeapNode<E>, x: FibonacciHeapNode<E>): void {\n this.removeFromRoot(y);\n y.left = y;\n y.right = y;\n this.mergeWithChild(x, y);\n x.degree++;\n y.parent = x;\n }\n\n protected _consolidate(): void {\n const A: (FibonacciHeapNode<E> | undefined)[] = new Array(this._size);\n const elements = this.consumeLinkedList(this.root);\n let x: FibonacciHeapNode<E> | undefined,\n y: FibonacciHeapNode<E> | undefined,\n d: number,\n t: FibonacciHeapNode<E> | undefined;\n\n for (const node of elements) {\n x = node;\n d = x.degree;\n while (A[d]) {\n y = A[d] as FibonacciHeapNode<E>;\n if (this.comparator(x.element, y.element) > 0) {\n t = x;\n x = y;\n y = t;\n }\n this._link(y, x);\n A[d] = undefined;\n d++;\n }\n A[d] = x;\n }\n\n for (let i = 0; i < A.length; i++) {\n if (A[i] && (!this.min || this.comparator(A[i]!.element, this.min.element) <= 0)) this._min = A[i]!;\n }\n }\n}\n","/**\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Max-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: The value of each parent node is greater than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MaxHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a max-heap. For objects, supply a custom comparator.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","/**\n * @remarks Time O(n log n), Space O(n).\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Min-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. MinHeap Properties: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. MinHeap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MinHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a min-heap.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\n\nimport type { PriorityQueueOptions } from '../../types';\nimport { Heap } from '../heap';\n\n/**\n * @example\n */\nexport class PriorityQueue<E = any, R = any> extends Heap<E, R> {\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Min-oriented priority queue (min-heap) built on {@link PriorityQueue}.\n * The queue removes the smallest element first under the provided comparator.\n * Provide a custom comparator if you store non-primitive objects.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MinPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a min-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Max-oriented priority queue (max-heap) built on {@link PriorityQueue}.\n * The default comparator orders primitive values in descending order. If you store objects,\n * you must provide a custom comparator via {@link PriorityQueueOptions}.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MaxPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a max-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @throws {TypeError} Thrown when using the default comparator with object elements (provide a custom comparator).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","export enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n // if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n // if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n"],"mappings":"8kBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,kBAAAC,EAAA,sBAAAC,EAAA,SAAAC,EAAA,YAAAC,EAAA,qBAAAC,EAAA,YAAAC,EAAA,qBAAAC,EAAA,kBAAAC,EAAA,UAAAC,ICaO,IAAeC,EAAf,KAAgE,CAU3D,YAAYC,EAA4C,CAclEC,EAAA,KAAU,gBAbR,GAAID,EAAS,CACX,GAAM,CAAE,YAAAE,CAAY,EAAIF,EACxB,GAAI,OAAOE,GAAgB,WAAY,KAAK,aAAeA,UAClDA,EAAa,MAAM,IAAI,UAAU,qCAAqC,CACjF,CACF,CAiBA,IAAI,aAAkD,CACpD,OAAO,KAAK,YACd,CAWA,EAAE,OAAO,QAAQ,KAAKC,EAAsC,CAC1D,MAAO,KAAK,aAAa,GAAGA,CAAI,CAClC,CASA,CAAC,QAA8B,CAC7B,QAAWC,KAAQ,KAAM,MAAMA,CACjC,CAaA,MAAMC,EAA2CC,EAA4B,CAC3E,IAAIC,EAAQ,EACZ,QAAWH,KAAQ,KACjB,GAAIE,IAAY,QACd,GAAI,CAACD,EAAUD,EAAMG,IAAS,IAAI,EAAG,MAAO,WAGxC,CADOF,EACH,KAAKC,EAASF,EAAMG,IAAS,IAAI,EAAG,MAAO,GAGvD,MAAO,EACT,CAYA,KAAKF,EAA2CC,EAA4B,CAC1E,IAAIC,EAAQ,EACZ,QAAWH,KAAQ,KACjB,GAAIE,IAAY,QACd,GAAID,EAAUD,EAAMG,IAAS,IAAI,EAAG,MAAO,WAEhCF,EACJ,KAAKC,EAASF,EAAMG,IAAS,IAAI,EAAG,MAAO,GAGtD,MAAO,EACT,C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MAAMD,EAAUC,CAAO,CACzB,CACF,ECrBO,IAAMC,EAAN,cAA8CC,CAAW,CAC9D,YAAYC,EAAsC,CAAC,EAAGC,EAAsC,CAC1F,MAAMD,EAAUC,CAAO,CACzB,CACF,ECAO,IAAMC,EAAN,cAAiDC,CAAoB,CAO1E,YAAYC,EAAsC,CAAC,EAAGC,EAAsC,CAC1F,MAAMD,EAAUC,CAAO,CACzB,CACF,ECVO,IAAMC,EAAN,cAAiDC,CAAoB,CAQ1E,YAAYC,EAAsC,CAAC,EAAGC,EAAsC,CAC1F,MAAMD,EAAU,CACd,WAAY,CAACE,EAAMC,IAAiB,CAClC,GAAI,OAAOD,GAAM,UAAY,OAAOC,GAAM,SACxC,MAAM,UACJ,0GACF,EAEF,OAAID,EAAIC,EAAU,EACdD,EAAIC,EAAU,GACX,CACT,EACA,GAAGF,CACL,CAAC,CACH,CACF,ECzCO,IAAKG,OACVA,IAAA,MAAQ,GAAR,QACAA,IAAA,QAAU,GAAV,UAFUA,OAAA,IAKCC,EAAN,KAAe,CACpB,YACSC,EACAC,EACAC,EAAsB,GACtBC,EAAuB,GAC9B,CAJO,SAAAH,EACA,UAAAC,EACA,gBAAAC,EACA,iBAAAC,CAIT,CAGA,UAAUC,EAAQC,EAA6C,CAC7D,IAAMC,EAAW,KAAK,WAAaD,EAAWD,EAAK,KAAK,GAAG,GAAK,EAAIC,EAAWD,EAAK,KAAK,GAAG,EAAI,EAC1FG,EAAY,KAAK,YAAcF,EAAWD,EAAK,KAAK,IAAI,GAAK,EAAIC,EAAWD,EAAK,KAAK,IAAI,EAAI,EACpG,OAAOE,GAAYC,CACrB,CACF","names":["src_exports","__export","DFSOperation","FibonacciHeap","FibonacciHeapNode","Heap","MaxHeap","MaxPriorityQueue","MinHeap","MinPriorityQueue","PriorityQueue","Range","IterableElementBase","options","__publicField","toElementFn","args","item","predicate","thisArg","index","callbackfn","element","ele","initialValue","iter","acc","first","value","Heap","_Heap","IterableElementBase","elements","options","__publicField","a","b","comparator","_a","element","flags","el","ok","value","last","index","i","predicate","idx","equals","order","result","_dfs","left","right","results","visited","cloned","x","top","next","callback","thisArg","out","toElementFn","rest","v","parent","parentItem","halfLength","minItem","Ctor","FibonacciHeapNode","degree","FibonacciHeap","node","head","started","z","heapToMerge","thisRoot","otherRoot","thisRootRight","otherRootLeft","y","A","d","t","MaxHeap","Heap","elements","options","a","b","MinHeap","Heap","elements","options","PriorityQueue","Heap","elements","options","MinPriorityQueue","PriorityQueue","elements","options","MaxPriorityQueue","PriorityQueue","elements","options","a","b","DFSOperation","Range","low","high","includeLow","includeHigh","key","comparator","lowCheck","highCheck"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/heap/heap.ts","../../src/data-structures/heap/max-heap.ts","../../src/data-structures/heap/min-heap.ts","../../src/data-structures/priority-queue/priority-queue.ts","../../src/data-structures/priority-queue/min-priority-queue.ts","../../src/data-structures/priority-queue/max-priority-queue.ts","../../src/common/index.ts"],"sourcesContent":["/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nexport * from './data-structures/priority-queue';\nexport * from './data-structures/heap';\nexport * from './types/data-structures/priority-queue';\nexport * from './types/data-structures/heap';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected readonly _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: Each node in a heap follows a specific order property, which varies depending on the type of heap:\n * Max Heap: The value of each parent node is greater than or equal to the value of its children.\n * Min Heap: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n * // basic Heap creation and add operation\n * // Create a min heap (default)\n * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);\n *\n * // Verify size\n * console.log(minHeap.size); // 6;\n *\n * // Add new element\n * minHeap.add(4);\n * console.log(minHeap.size); // 7;\n *\n * // Min heap property: smallest element at root\n * const min = minHeap.peek();\n * console.log(min); // 1;\n * @example\n * // Heap with custom comparator (MaxHeap behavior)\n * interface Task {\n * id: number;\n * priority: number;\n * name: string;\n * }\n *\n * // Custom comparator for max heap behavior (higher priority first)\n * const tasks: Task[] = [\n * { id: 1, priority: 5, name: 'Email' },\n * { id: 2, priority: 3, name: 'Chat' },\n * { id: 3, priority: 8, name: 'Alert' }\n * ];\n *\n * const maxHeap = new Heap(tasks, {\n * comparator: (a: Task, b: Task) => b.priority - a.priority\n * });\n *\n * console.log(maxHeap.size); // 3;\n *\n * // Peek returns highest priority task\n * const topTask = maxHeap.peek();\n * console.log(topTask?.priority); // 8;\n * console.log(topTask?.name); // 'Alert';\n * @example\n * // Heap for event processing with priority\n * interface Event {\n * id: number;\n * type: 'critical' | 'warning' | 'info';\n * timestamp: number;\n * message: string;\n * }\n *\n * // Custom priority: critical > warning > info\n * const priorityMap = { critical: 3, warning: 2, info: 1 };\n *\n * const eventHeap = new Heap<Event>([], {\n * comparator: (a: Event, b: Event) => {\n * const priorityA = priorityMap[a.type];\n * const priorityB = priorityMap[b.type];\n * return priorityB - priorityA; // Higher priority first\n * }\n * });\n *\n * // Add events in random order\n * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });\n * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });\n * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });\n * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });\n * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });\n *\n * console.log(eventHeap.size); // 5;\n *\n * // Process events by priority (critical first)\n * const processedOrder: Event[] = [];\n * while (eventHeap.size > 0) {\n * const event = eventHeap.poll();\n * if (event) {\n * processedOrder.push(event);\n * }\n * }\n *\n * // Verify critical events came first\n * console.log(processedOrder[0].type); // 'critical';\n * console.log(processedOrder[1].type); // 'critical';\n * console.log(processedOrder[2].type); // 'warning';\n * console.log(processedOrder[3].type); // 'info';\n * console.log(processedOrder[4].type); // 'info';\n *\n * // Verify O(log n) operations\n * const newHeap = new Heap<number>([5, 3, 7, 1]);\n *\n * // Add - O(log n)\n * newHeap.add(2);\n * console.log(newHeap.size); // 5;\n *\n * // Poll - O(log n)\n * const removed = newHeap.poll();\n * console.log(removed); // 1;\n *\n * // Peek - O(1)\n * const top = newHeap.peek();\n * console.log(top); // 2;\n * @example\n * // Use Heap to solve top k problems\n * function topKElements(arr: number[], k: number): number[] {\n * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap\n * arr.forEach(num => {\n * heap.add(num);\n * if (heap.size > k) heap.poll(); // Keep the heap size at K\n * });\n * return heap.toArray();\n * }\n *\n * const numbers = [10, 30, 20, 5, 15, 25];\n * console.log(topKElements(numbers, 3)); // [15, 10, 5];\n * @example\n * // Use Heap to dynamically maintain the median\n * class MedianFinder {\n * private low: MaxHeap<number>; // Max heap, stores the smaller half\n * private high: MinHeap<number>; // Min heap, stores the larger half\n *\n * constructor() {\n * this.low = new MaxHeap<number>([]);\n * this.high = new MinHeap<number>([]);\n * }\n *\n * addNum(num: number): void {\n * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);\n * else this.high.add(num);\n *\n * // Balance heaps\n * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);\n * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);\n * }\n *\n * findMedian(): number {\n * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;\n * return this.low.peek()!;\n * }\n * }\n *\n * const medianFinder = new MedianFinder();\n * medianFinder.addNum(10);\n * console.log(medianFinder.findMedian()); // 10;\n * medianFinder.addNum(20);\n * console.log(medianFinder.findMedian()); // 15;\n * medianFinder.addNum(30);\n * console.log(medianFinder.findMedian()); // 20;\n * medianFinder.addNum(40);\n * console.log(medianFinder.findMedian()); // 25;\n * medianFinder.addNum(50);\n * console.log(medianFinder.findMedian()); // 30;\n * @example\n * // Use Heap for load balancing\n * function loadBalance(requests: number[], servers: number): number[] {\n * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap\n * const serverLoads = new Array(servers).fill(0);\n *\n * for (let i = 0; i < servers; i++) {\n * serverHeap.add({ id: i, load: 0 });\n * }\n *\n * requests.forEach(req => {\n * const server = serverHeap.poll()!;\n * serverLoads[server.id] += req;\n * server.load += req;\n * serverHeap.add(server); // The server after updating the load is re-entered into the heap\n * });\n *\n * return serverLoads;\n * }\n *\n * const requests = [5, 2, 8, 3, 7];\n * console.log(loadBalance(requests, 3)); // [12, 8, 5];\n * @example\n * // Use Heap to schedule tasks\n * type Task = [string, number];\n *\n * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {\n * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap\n * const allocation = new Map<number, Task[]>();\n *\n * // Initialize the load on each machine\n * for (let i = 0; i < machines; i++) {\n * machineHeap.add({ id: i, load: 0 });\n * allocation.set(i, []);\n * }\n *\n * // Assign tasks\n * tasks.forEach(([task, load]) => {\n * const machine = machineHeap.poll()!;\n * allocation.get(machine.id)!.push([task, load]);\n * machine.load += load;\n * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap\n * });\n *\n * return allocation;\n * }\n *\n * const tasks: Task[] = [\n * ['Task1', 3],\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task4', 5],\n * ['Task5', 4]\n * ];\n * const expectedMap = new Map<number, Task[]>();\n * expectedMap.set(0, [\n * ['Task1', 3],\n * ['Task4', 5]\n * ]);\n * expectedMap.set(1, [\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task5', 4]\n * ]);\n * console.log(scheduleTasks(tasks, 2)); // expectedMap;\n */\nexport class Heap<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is;\n\n /**\n * Create a Heap and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw values if toElementFn is set).\n * @param [options] - Options such as comparator and toElementFn.\n * @returns New Heap instance.\n */\n\n constructor(elements: Iterable<E | R> = [], options?: HeapOptions<E, R>) {\n super(options);\n\n if (options) {\n const { comparator } = options;\n if (comparator) this._comparator = comparator;\n }\n\n this.addMany(elements as Iterable<E | R>);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of the heap.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Heap size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Get the last leaf element.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get leaf(): E | undefined {\n return this.elements[this.size - 1] ?? undefined;\n }\n\n /**\n * Create a heap of the same class from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template R\n * @template S\n * @param [elements] - Iterable of elements or raw records.\n * @param [options] - Heap options including comparator.\n * @returns A new heap instance of this class.\n */\n\n static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(\n this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,\n elements?: Iterable<T | R>,\n options?: HeapOptions<T, R>\n ): S {\n return new this(elements, options);\n }\n\n /**\n * Build a Heap from an iterable in linear time given a comparator.\n * @remarks Time O(N), Space O(N)\n * @template EE\n * @template RR\n * @param elements - Iterable of elements.\n * @param options - Heap options including comparator.\n * @returns A new Heap built from elements.\n */\n\n static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {\n return new Heap<EE, RR>(elements, options);\n }\n\n /**\n * Insert an element.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns True.\n */\n\n add(element: E): boolean {\n this._elements.push(element);\n return this._bubbleUp(this.elements.length - 1);\n }\n\n /**\n * Insert many elements from an iterable.\n * @remarks Time O(N log N), Space O(1)\n * @param elements - Iterable of elements or raw values.\n * @returns Array of per-element success flags.\n */\n\n addMany(elements: Iterable<E | R>): boolean[] {\n const flags: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n const ok = this.add(this.toElementFn(el as R));\n flags.push(ok);\n } else {\n const ok = this.add(el as E);\n flags.push(ok);\n }\n }\n return flags;\n }\n\n /**\n * Remove and return the top element.\n * @remarks Time O(log N), Space O(1)\n * @returns Top element or undefined.\n */\n\n poll(): E | undefined {\n if (this.elements.length === 0) return;\n const value = this.elements[0];\n const last = this.elements.pop()!;\n if (this.elements.length) {\n this.elements[0] = last;\n this._sinkDown(0, this.elements.length >> 1);\n }\n return value;\n }\n\n /**\n * Get the current top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.elements[0];\n }\n\n /**\n * Check whether the heap is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Remove all elements.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Replace the backing array and rebuild the heap.\n * @remarks Time O(N), Space O(N)\n * @param elements - Iterable used to refill the heap.\n * @returns Array of per-node results from fixing steps.\n */\n\n refill(elements: Iterable<E>): boolean[] {\n this._elements = Array.from(elements);\n return this.fix();\n }\n\n /**\n * Check if an equal element exists in the heap.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to search for.\n * @returns True if found.\n */\n\n override has(element: E): boolean {\n for (const el of this.elements) if (this._equals(el, element)) return true;\n return false;\n }\n\n /**\n * Delete one occurrence of an element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to delete.\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n let index = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (this._equals(this.elements[i], element)) {\n index = i;\n break;\n }\n }\n if (index < 0) return false;\n if (index === 0) {\n this.poll();\n } else if (index === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(index, 1, this.elements.pop()!);\n this._bubbleUp(index);\n this._sinkDown(index, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Delete the first element that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (element, index, heap) → boolean.\n * @returns True if an element was removed.\n */\n\n deleteBy(predicate: (element: E, index: number, heap: this) => boolean): boolean {\n let idx = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n idx = i;\n break;\n }\n }\n if (idx < 0) return false;\n if (idx === 0) {\n this.poll();\n } else if (idx === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(idx, 1, this.elements.pop()!);\n this._bubbleUp(idx);\n this._sinkDown(idx, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Set the equality comparator used by has/delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This heap.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Traverse the binary heap as a complete binary tree and collect elements.\n * @remarks Time O(N), Space O(H)\n * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.\n * @returns Array of visited elements.\n */\n\n dfs(order: DFSOrderPattern = 'PRE'): E[] {\n const result: E[] = [];\n const _dfs = (index: number) => {\n const left = 2 * index + 1,\n right = left + 1;\n if (index < this.size) {\n if (order === 'IN') {\n _dfs(left);\n result.push(this.elements[index]);\n _dfs(right);\n } else if (order === 'PRE') {\n result.push(this.elements[index]);\n _dfs(left);\n _dfs(right);\n } else if (order === 'POST') {\n _dfs(left);\n _dfs(right);\n result.push(this.elements[index]);\n }\n }\n };\n _dfs(0);\n return result;\n }\n\n /**\n * Restore heap order bottom-up (heapify in-place).\n * @remarks Time O(N), Space O(1)\n * @returns Array of per-node results from fixing steps.\n */\n\n fix(): boolean[] {\n const results: boolean[] = [];\n for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {\n results.push(this._sinkDown(i, this.elements.length >> 1));\n }\n return results;\n }\n\n /**\n * Return all elements in ascending order by repeatedly polling.\n * @remarks Time O(N log N), Space O(N)\n * @returns Sorted array of elements.\n */\n\n sort(): E[] {\n const visited: E[] = [];\n const cloned = this._createInstance();\n for (const x of this.elements) cloned.add(x);\n while (!cloned.isEmpty()) {\n const top = cloned.poll();\n if (top !== undefined) visited.push(top);\n }\n return visited;\n }\n\n /**\n * Deep clone this heap.\n * @remarks Time O(N), Space O(N)\n * @returns A new heap with the same elements.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this.elements) next.add(x);\n return next;\n }\n\n /**\n * Filter elements into a new heap of the same class.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Predicate (element, index, heap) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with the kept elements.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n if (thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {\n out.add(x);\n } else {\n i++;\n }\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of possibly different element type.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, heap) → newElement.\n * @param options - Options for the output heap, including comparator for EM.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options: HeapOptions<EM, RM> & { comparator: Comparator<EM> },\n thisArg?: unknown\n ): Heap<EM, RM> {\n const { comparator, toElementFn, ...rest } = options ?? {};\n if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');\n const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of the same element type.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Mapping function (element, index, heap) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n protected readonly _DEFAULT_COMPARATOR: Comparator<E> = (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError('When comparing object types, define a custom comparator in options.');\n }\n if (a > b) return 1;\n if (a < b) return -1;\n return 0;\n };\n\n protected readonly _comparator: Comparator<E> = this._DEFAULT_COMPARATOR;\n\n /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n\n get comparator() {\n return this._comparator;\n }\n\n protected *_getIterator(): IterableIterator<E> {\n for (const element of this.elements) yield element;\n }\n\n protected _bubbleUp(index: number): boolean {\n const element = this.elements[index];\n while (index > 0) {\n const parent = (index - 1) >> 1;\n const parentItem = this.elements[parent];\n if (this.comparator(parentItem, element) <= 0) break;\n this.elements[index] = parentItem;\n index = parent;\n }\n this.elements[index] = element;\n return true;\n }\n\n protected _sinkDown(index: number, halfLength: number): boolean {\n const element = this.elements[index];\n while (index < halfLength) {\n let left = (index << 1) | 1;\n const right = left + 1;\n let minItem = this.elements[left];\n if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {\n left = right;\n minItem = this.elements[right];\n }\n if (this.comparator(minItem, element) >= 0) break;\n this.elements[index] = minItem;\n index = left;\n }\n this.elements[index] = element;\n return true;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options to override comparator or toElementFn.\n * @returns A like-kind empty heap instance.\n */\n\n protected _createInstance(options?: HeapOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R>,\n options?: HeapOptions<E, R>\n ) => this;\n return new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...(options ?? {}) });\n }\n\n /**\n * (Protected) Create a like-kind instance seeded by elements.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable of elements or raw values to seed.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind heap instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: HeapOptions<EM, RM>\n ): Heap<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: HeapOptions<EM, RM>\n ) => Heap<EM, RM>;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Spawn an empty like-kind heap instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind heap instance.\n */\n\n protected _spawnLike<EM, RM>(options?: HeapOptions<EM, RM>): Heap<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\n/**\n * Node container used by FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class FibonacciHeapNode<E> {\n element: E;\n degree: number;\n left?: FibonacciHeapNode<E>;\n right?: FibonacciHeapNode<E>;\n child?: FibonacciHeapNode<E>;\n parent?: FibonacciHeapNode<E>;\n marked: boolean;\n\n constructor(element: E, degree = 0) {\n this.element = element;\n this.degree = degree;\n this.marked = false;\n }\n}\n\n/**\n * Fibonacci heap (min-heap) optimized for fast merges and amortized operations.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @example examples will be generated by unit test\n */\nexport class FibonacciHeap<E> {\n /**\n * Create a FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @param [comparator] - Comparator to order elements (min-heap by default).\n * @returns New FibonacciHeap instance.\n */\n\n constructor(comparator?: Comparator<E>) {\n this.clear();\n this._comparator = comparator || this._defaultComparator;\n if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');\n }\n\n protected _root?: FibonacciHeapNode<E>;\n\n /**\n * Get the circular root list head.\n * @remarks Time O(1), Space O(1)\n * @returns Root node or undefined.\n */\n\n get root(): FibonacciHeapNode<E> | undefined {\n return this._root;\n }\n\n protected _size = 0;\n get size(): number {\n return this._size;\n }\n\n protected _min?: FibonacciHeapNode<E>;\n\n /**\n * Get the current minimum node.\n * @remarks Time O(1), Space O(1)\n * @returns Min node or undefined.\n */\n\n get min(): FibonacciHeapNode<E> | undefined {\n return this._min;\n }\n\n protected readonly _comparator: Comparator<E>;\n\n get comparator(): Comparator<E> {\n return this._comparator;\n }\n\n clear(): void {\n this._root = undefined;\n this._min = undefined;\n this._size = 0;\n }\n\n add(element: E): boolean {\n this.push(element);\n return true;\n }\n\n /**\n * Push an element into the root list.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns This heap.\n */\n\n push(element: E): this {\n const node = this.createNode(element);\n node.left = node;\n node.right = node;\n this.mergeWithRoot(node);\n if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;\n this._size++;\n return this;\n }\n\n peek(): E | undefined {\n return this.min ? this.min.element : undefined;\n }\n\n /**\n * Collect nodes from a circular doubly linked list starting at head.\n * @remarks Time O(K), Space O(K)\n * @param [head] - Start node of the circular list.\n * @returns Array of nodes from the list.\n */\n\n consumeLinkedList(head?: FibonacciHeapNode<E>): FibonacciHeapNode<E>[] {\n const elements: FibonacciHeapNode<E>[] = [];\n if (!head) return elements;\n let node: FibonacciHeapNode<E> | undefined = head;\n let started = false;\n while (true) {\n if (node === head && started) break;\n else if (node === head) started = true;\n elements.push(node!);\n node = node!.right;\n }\n return elements;\n }\n\n /**\n * Insert a node into a parent's child list (circular).\n * @remarks Time O(1), Space O(1)\n * @param parent - Parent node.\n * @param node - Child node to insert.\n * @returns void\n */\n\n mergeWithChild(parent: FibonacciHeapNode<E>, node: FibonacciHeapNode<E>): void {\n if (!parent.child) parent.child = node;\n else {\n node.right = parent.child.right;\n node.left = parent.child;\n parent.child.right!.left = node;\n parent.child.right = node;\n }\n }\n\n poll(): E | undefined {\n return this.pop();\n }\n\n /**\n * Remove and return the minimum element, consolidating the root list.\n * @remarks Time O(log N) amortized, Space O(1)\n * @returns Minimum element or undefined.\n */\n\n pop(): E | undefined {\n if (this._size === 0) return undefined;\n const z = this.min!;\n if (z.child) {\n const elements = this.consumeLinkedList(z.child);\n for (const node of elements) {\n this.mergeWithRoot(node);\n node.parent = undefined;\n }\n }\n this.removeFromRoot(z);\n if (z === z.right) {\n this._min = undefined;\n this._root = undefined;\n } else {\n this._min = z.right;\n this._consolidate();\n }\n this._size--;\n return z.element;\n }\n\n /**\n * Meld another heap into this heap.\n * @remarks Time O(1), Space O(1)\n * @param heapToMerge - Another FibonacciHeap to meld into this one.\n * @returns void\n */\n\n merge(heapToMerge: FibonacciHeap<E>): void {\n if (heapToMerge.size === 0) return;\n if (this.root && heapToMerge.root) {\n const thisRoot = this.root,\n otherRoot = heapToMerge.root;\n const thisRootRight = thisRoot.right!,\n otherRootLeft = otherRoot.left!;\n thisRoot.right = otherRoot;\n otherRoot.left = thisRoot;\n thisRootRight.left = otherRootLeft;\n otherRootLeft.right = thisRootRight;\n } else if (!this.root && heapToMerge.root) {\n this._root = heapToMerge.root;\n }\n if (!this.min || (heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0)) {\n this._min = heapToMerge.min;\n }\n this._size += heapToMerge.size;\n heapToMerge.clear();\n }\n\n createNode(element: E): FibonacciHeapNode<E> {\n return new FibonacciHeapNode<E>(element);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n protected _defaultComparator(a: E, b: E): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n protected mergeWithRoot(node: FibonacciHeapNode<E>): void {\n if (!this.root) this._root = node;\n else {\n node.right = this.root.right;\n node.left = this.root;\n this.root.right!.left = node;\n this.root.right = node;\n }\n }\n\n protected removeFromRoot(node: FibonacciHeapNode<E>): void {\n if (this.root === node) this._root = node.right;\n if (node.left) node.left.right = node.right;\n if (node.right) node.right.left = node.left;\n }\n\n protected _link(y: FibonacciHeapNode<E>, x: FibonacciHeapNode<E>): void {\n this.removeFromRoot(y);\n y.left = y;\n y.right = y;\n this.mergeWithChild(x, y);\n x.degree++;\n y.parent = x;\n }\n\n protected _consolidate(): void {\n const A: (FibonacciHeapNode<E> | undefined)[] = new Array(this._size);\n const elements = this.consumeLinkedList(this.root);\n let x: FibonacciHeapNode<E> | undefined,\n y: FibonacciHeapNode<E> | undefined,\n d: number,\n t: FibonacciHeapNode<E> | undefined;\n\n for (const node of elements) {\n x = node;\n d = x.degree;\n while (A[d]) {\n y = A[d] as FibonacciHeapNode<E>;\n if (this.comparator(x.element, y.element) > 0) {\n t = x;\n x = y;\n y = t;\n }\n this._link(y, x);\n A[d] = undefined;\n d++;\n }\n A[d] = x;\n }\n\n for (let i = 0; i < A.length; i++) {\n if (A[i] && (!this.min || this.comparator(A[i]!.element, this.min.element) <= 0)) this._min = A[i]!;\n }\n }\n}\n","/**\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Max-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: The value of each parent node is greater than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MaxHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a max-heap. For objects, supply a custom comparator.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","/**\n * @remarks Time O(n log n), Space O(n).\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Min-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. MinHeap Properties: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. MinHeap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MinHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a min-heap.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\n\nimport type { PriorityQueueOptions } from '../../types';\nimport { Heap } from '../heap';\n\n/**\n * @example\n */\nexport class PriorityQueue<E = any, R = any> extends Heap<E, R> {\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Min-oriented priority queue (min-heap) built on {@link PriorityQueue}.\n * The queue removes the smallest element first under the provided comparator.\n * Provide a custom comparator if you store non-primitive objects.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MinPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a min-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Max-oriented priority queue (max-heap) built on {@link PriorityQueue}.\n * The default comparator orders primitive values in descending order. If you store objects,\n * you must provide a custom comparator via {@link PriorityQueueOptions}.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MaxPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a max-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @throws {TypeError} Thrown when using the default comparator with object elements (provide a custom comparator).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","export enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n // if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n // if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n"],"mappings":"8kBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,kBAAAC,EAAA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EAAN,cAAiDC,CAAoB,CAQ1E,YAAYC,EAAsC,CAAC,EAAGC,EAAsC,CAC1F,MAAMD,EAAU,CACd,WAAY,CAACE,EAAMC,IAAiB,CAClC,GAAI,OAAOD,GAAM,UAAY,OAAOC,GAAM,SACxC,MAAM,UACJ,0GACF,EAEF,OAAID,EAAIC,EAAU,EACdD,EAAIC,EAAU,GACX,CACT,EACA,GAAGF,CACL,CAAC,CACH,CACF,ECzCO,IAAKG,OACVA,IAAA,MAAQ,GAAR,QACAA,IAAA,QAAU,GAAV,UAFUA,OAAA,IAKCC,EAAN,KAAe,CACpB,YACSC,EACAC,EACAC,EAAsB,GACtBC,EAAuB,GAC9B,CAJO,SAAAH,EACA,UAAAC,EACA,gBAAAC,EACA,iBAAAC,CAIT,CAGA,UAAUC,EAAQC,EAA6C,CAC7D,IAAMC,EAAW,KAAK,WAAaD,EAAWD,EAAK,KAAK,GAAG,GAAK,EAAIC,EAAWD,EAAK,KAAK,GAAG,EAAI,EAC1FG,EAAY,KAAK,YAAcF,EAAWD,EAAK,KAAK,IAAI,GAAK,EAAIC,EAAWD,EAAK,KAAK,IAAI,EAAI,EACpG,OAAOE,GAAYC,CACrB,CACF","names":["src_exports","__export","DFSOperation","FibonacciHeap","FibonacciHeapNode","Heap","MaxHeap","MaxPriorityQueue","MinHeap","MinPriorityQueue","PriorityQueue","Range","IterableElementBase","options","__publicField","toElementFn","args","item","predicate","thisArg","index","callbackfn","element","ele","initialValue","iter","acc","first","value","Heap","_Heap","IterableElementBase","elements","options","__publicField","a","b","comparator","_a","element","flags","el","ok","value","last","index","i","predicate","idx","equals","order","result","_dfs","left","right","results","visited","cloned","x","top","next","callback","thisArg","out","toElementFn","rest","v","parent","parentItem","halfLength","minItem","Ctor","FibonacciHeapNode","degree","FibonacciHeap","node","head","started","z","heapToMerge","thisRoot","otherRoot","thisRootRight","otherRootLeft","y","A","d","t","MaxHeap","Heap","elements","options","a","b","MinHeap","Heap","elements","options","PriorityQueue","Heap","elements","options","MinPriorityQueue","PriorityQueue","elements","options","MaxPriorityQueue","PriorityQueue","elements","options","a","b","DFSOperation","Range","low","high","includeLow","includeHigh","key","comparator","lowCheck","highCheck"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "priority-queue-typed",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.4",
|
|
4
4
|
"description": "Priority Queue",
|
|
5
5
|
"browser": "dist/umd/priority-queue-typed.min.js",
|
|
6
6
|
"umd:main": "dist/umd/priority-queue-typed.min.js",
|
|
@@ -158,6 +158,6 @@
|
|
|
158
158
|
"typedoc": "^0.25.1"
|
|
159
159
|
},
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"data-structure-typed": "^2.4.
|
|
161
|
+
"data-structure-typed": "^2.4.4"
|
|
162
162
|
}
|
|
163
163
|
}
|
|
@@ -35,7 +35,7 @@ export abstract class IterableElementBase<E, R> implements Iterable<E> {
|
|
|
35
35
|
* @remarks
|
|
36
36
|
* Time O(1), Space O(1).
|
|
37
37
|
*/
|
|
38
|
-
protected _toElementFn?: (rawElement: R) => E;
|
|
38
|
+
protected readonly _toElementFn?: (rawElement: R) => E;
|
|
39
39
|
|
|
40
40
|
/**
|
|
41
41
|
* Exposes the current `toElementFn`, if configured.
|
|
@@ -229,7 +229,7 @@ export abstract class IterableElementBase<E, R> implements Iterable<E> {
|
|
|
229
229
|
index = 1;
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
-
for (const value of iter
|
|
232
|
+
for (const value of iter) {
|
|
233
233
|
acc = callbackfn(acc, value, index++, this);
|
|
234
234
|
}
|
|
235
235
|
return acc;
|
|
@@ -377,7 +377,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
377
377
|
if (keysNodesEntriesOrRaws) this.setMany(keysNodesEntriesOrRaws);
|
|
378
378
|
}
|
|
379
379
|
|
|
380
|
-
protected _isMapMode = true;
|
|
380
|
+
protected readonly _isMapMode: boolean = true;
|
|
381
381
|
|
|
382
382
|
/**
|
|
383
383
|
* Gets whether the tree is in Map mode.
|
|
@@ -389,7 +389,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
389
389
|
return this._isMapMode;
|
|
390
390
|
}
|
|
391
391
|
|
|
392
|
-
protected _isDuplicate = false;
|
|
392
|
+
protected readonly _isDuplicate: boolean = false;
|
|
393
393
|
|
|
394
394
|
/**
|
|
395
395
|
* Gets whether the tree allows duplicate keys.
|
|
@@ -440,7 +440,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
440
440
|
return this._size;
|
|
441
441
|
}
|
|
442
442
|
|
|
443
|
-
protected _NIL
|
|
443
|
+
protected readonly _NIL = new BinaryTreeNode<K, V>(NaN as K);
|
|
444
444
|
|
|
445
445
|
/**
|
|
446
446
|
* Gets the sentinel NIL node (used in self-balancing trees like Red-Black Tree).
|
|
@@ -452,7 +452,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
452
452
|
return this._NIL;
|
|
453
453
|
}
|
|
454
454
|
|
|
455
|
-
protected _toEntryFn?: ToEntryFn<K, V, R>;
|
|
455
|
+
protected readonly _toEntryFn?: ToEntryFn<K, V, R>;
|
|
456
456
|
|
|
457
457
|
/**
|
|
458
458
|
* Gets the function used to convert raw data objects (R) into [key, value] entries.
|
|
@@ -1014,7 +1014,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
1014
1014
|
): BinaryTreeNode<K, V> | null | undefined {
|
|
1015
1015
|
if (this._isMapMode && keyNodeEntryOrPredicate !== null && keyNodeEntryOrPredicate !== undefined) {
|
|
1016
1016
|
if (!this._isPredicate(keyNodeEntryOrPredicate)) {
|
|
1017
|
-
const key = this._extractKey(keyNodeEntryOrPredicate
|
|
1017
|
+
const key = this._extractKey(keyNodeEntryOrPredicate);
|
|
1018
1018
|
if (key === null || key === undefined) return;
|
|
1019
1019
|
return this._store.get(key);
|
|
1020
1020
|
}
|
|
@@ -1078,7 +1078,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
1078
1078
|
): boolean {
|
|
1079
1079
|
if (this._isMapMode && keyNodeEntryOrPredicate !== undefined && keyNodeEntryOrPredicate !== null) {
|
|
1080
1080
|
if (!this._isPredicate(keyNodeEntryOrPredicate)) {
|
|
1081
|
-
const key = this._extractKey(keyNodeEntryOrPredicate
|
|
1081
|
+
const key = this._extractKey(keyNodeEntryOrPredicate);
|
|
1082
1082
|
if (key === null || key === undefined) return false;
|
|
1083
1083
|
return this._store.has(key);
|
|
1084
1084
|
}
|
|
@@ -2136,7 +2136,8 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
2136
2136
|
* @param node - The node.
|
|
2137
2137
|
* @returns The node's key or undefined.
|
|
2138
2138
|
*/
|
|
2139
|
-
protected _DEFAULT_NODE_CALLBACK
|
|
2139
|
+
protected readonly _DEFAULT_NODE_CALLBACK: NodeCallback<BinaryTreeNode<K, V> | null | undefined, K | undefined> =
|
|
2140
|
+
(node): K | undefined => node?.key;
|
|
2140
2141
|
|
|
2141
2142
|
/**
|
|
2142
2143
|
* (Protected) Snapshots the current tree's configuration options.
|
|
@@ -391,7 +391,7 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
|
|
|
391
391
|
|
|
392
392
|
* @remarks Time O(1) Space O(1)
|
|
393
393
|
*/
|
|
394
|
-
protected _comparator: Comparator<K>;
|
|
394
|
+
protected readonly _comparator: Comparator<K>;
|
|
395
395
|
|
|
396
396
|
/**
|
|
397
397
|
* Gets the comparator function used by the tree.
|
|
@@ -436,4 +436,20 @@ export class TreeMap<K = any, V = any, R = [K, V]> implements Iterable<[K, V | u
|
|
|
436
436
|
|
|
437
437
|
return out;
|
|
438
438
|
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Creates a shallow clone of this map.
|
|
442
|
+
* @remarks Time O(n log n), Space O(n)
|
|
443
|
+
* @example
|
|
444
|
+
* const original = new TreeMap([['a', 1], ['b', 2]]);
|
|
445
|
+
* const copy = original.clone();
|
|
446
|
+
* copy.set('c', 3);
|
|
447
|
+
* original.has('c'); // false (original unchanged)
|
|
448
|
+
*/
|
|
449
|
+
clone(): TreeMap<K, V> {
|
|
450
|
+
return new TreeMap<K, V>(this, {
|
|
451
|
+
comparator: this.#isDefaultComparator ? undefined : this.#userComparator,
|
|
452
|
+
isMapMode: this.#core.isMapMode
|
|
453
|
+
});
|
|
454
|
+
}
|
|
439
455
|
}
|
|
@@ -247,7 +247,7 @@ export class TreeMultiSet<K = any, R = K> implements Iterable<K> {
|
|
|
247
247
|
* @remarks Time O(1), Space O(1)
|
|
248
248
|
*/
|
|
249
249
|
get comparator(): Comparator<K> {
|
|
250
|
-
return
|
|
250
|
+
return this.#core.comparator;
|
|
251
251
|
}
|
|
252
252
|
|
|
253
253
|
// ━━━ clear ━━━
|
|
@@ -398,7 +398,7 @@ export class TreeMultiSet<K = any, R = K> implements Iterable<K> {
|
|
|
398
398
|
filter(predicate: (key: K, count: number) => boolean): TreeMultiSet<K> {
|
|
399
399
|
const result = new TreeMultiSet<K>([], {
|
|
400
400
|
comparator: this.#isDefaultComparator ? undefined : this.comparator,
|
|
401
|
-
isMapMode:
|
|
401
|
+
isMapMode: this.#core.isMapMode
|
|
402
402
|
});
|
|
403
403
|
for (const [k, c] of this.entries()) {
|
|
404
404
|
if (predicate(k, c)) {
|
|
@@ -443,7 +443,7 @@ export class TreeMultiSet<K = any, R = K> implements Iterable<K> {
|
|
|
443
443
|
): TreeMultiSet<K2> {
|
|
444
444
|
const result = new TreeMultiSet<K2>([], {
|
|
445
445
|
comparator: options?.comparator,
|
|
446
|
-
isMapMode:
|
|
446
|
+
isMapMode: this.#core.isMapMode
|
|
447
447
|
});
|
|
448
448
|
for (const [k, c] of this.entries()) {
|
|
449
449
|
const [newKey, newCount] = mapper(k, c);
|
|
@@ -464,7 +464,7 @@ export class TreeMultiSet<K = any, R = K> implements Iterable<K> {
|
|
|
464
464
|
clone(): TreeMultiSet<K> {
|
|
465
465
|
const result = new TreeMultiSet<K>([], {
|
|
466
466
|
comparator: this.#isDefaultComparator ? undefined : this.comparator,
|
|
467
|
-
isMapMode:
|
|
467
|
+
isMapMode: this.#core.isMapMode
|
|
468
468
|
});
|
|
469
469
|
for (const [k, c] of this.entries()) {
|
|
470
470
|
result.add(k, c);
|
|
@@ -486,7 +486,7 @@ export class TreeMultiSet<K = any, R = K> implements Iterable<K> {
|
|
|
486
486
|
callback?: C
|
|
487
487
|
): (C extends undefined ? K : ReturnType<C>)[] {
|
|
488
488
|
const cb = callback ?? ((k: K) => k);
|
|
489
|
-
return this.#core.rangeSearch(range, node => cb(node.key))
|
|
489
|
+
return this.#core.rangeSearch(range, node => cb(node.key));
|
|
490
490
|
}
|
|
491
491
|
|
|
492
492
|
/**
|
|
@@ -404,4 +404,20 @@ export class TreeSet<K = any, R = K> implements Iterable<K> {
|
|
|
404
404
|
|
|
405
405
|
return out;
|
|
406
406
|
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Creates a shallow clone of this set.
|
|
410
|
+
* @remarks Time O(n log n), Space O(n)
|
|
411
|
+
* @example
|
|
412
|
+
* const original = new TreeSet([1, 2, 3]);
|
|
413
|
+
* const copy = original.clone();
|
|
414
|
+
* copy.add(4);
|
|
415
|
+
* original.has(4); // false (original unchanged)
|
|
416
|
+
*/
|
|
417
|
+
clone(): TreeSet<K> {
|
|
418
|
+
return new TreeSet<K>(this, {
|
|
419
|
+
comparator: this.#isDefaultComparator ? undefined : this.#userComparator,
|
|
420
|
+
isMapMode: this.#core.isMapMode
|
|
421
|
+
});
|
|
422
|
+
}
|
|
407
423
|
}
|
|
@@ -65,7 +65,7 @@ export abstract class AbstractGraph<
|
|
|
65
65
|
*/
|
|
66
66
|
constructor(options?: Partial<Record<string, unknown>>) {
|
|
67
67
|
super();
|
|
68
|
-
const graph = (options as
|
|
68
|
+
const graph = (options as { graph?: GraphOptions<V> })?.graph;
|
|
69
69
|
this._options = { defaultEdgeWeight: 1, ...(graph ?? {}) };
|
|
70
70
|
}
|
|
71
71
|
|
|
@@ -984,11 +984,12 @@ export abstract class AbstractGraph<
|
|
|
984
984
|
* @remarks Time O(1), Space O(1)
|
|
985
985
|
*/
|
|
986
986
|
protected _createInstance(_options?: Partial<Record<string, unknown>>): this {
|
|
987
|
-
const Ctor
|
|
988
|
-
const instance
|
|
989
|
-
const graph = (_options as
|
|
990
|
-
|
|
991
|
-
|
|
987
|
+
const Ctor = this.constructor as new () => this;
|
|
988
|
+
const instance = new Ctor();
|
|
989
|
+
const graph = (_options as { graph?: GraphOptions<V> })?.graph;
|
|
990
|
+
// Use bracket notation for protected field access on dynamically created instance
|
|
991
|
+
if (graph) instance['_options'] = { ...instance['_options'], ...graph };
|
|
992
|
+
else instance['_options'] = { ...instance['_options'], ...this._options };
|
|
992
993
|
return instance;
|
|
993
994
|
}
|
|
994
995
|
|
|
@@ -1009,28 +1010,27 @@ export abstract class AbstractGraph<
|
|
|
1009
1010
|
// 1) Add vertices
|
|
1010
1011
|
if (iter) {
|
|
1011
1012
|
for (const [k, v] of iter) {
|
|
1012
|
-
|
|
1013
|
+
g.addVertex(k as VertexKey, v as V | undefined);
|
|
1013
1014
|
}
|
|
1014
1015
|
} else {
|
|
1015
1016
|
for (const [k, v] of this) {
|
|
1016
|
-
|
|
1017
|
+
g.addVertex(k as VertexKey, v as V | undefined);
|
|
1017
1018
|
}
|
|
1018
1019
|
}
|
|
1019
1020
|
// 2) Add edges whose endpoints exist in the new graph
|
|
1020
1021
|
const edges = this.edgeSet();
|
|
1021
|
-
for (const e of edges
|
|
1022
|
-
const ends = this.getEndsOfEdge(e
|
|
1022
|
+
for (const e of edges) {
|
|
1023
|
+
const ends = this.getEndsOfEdge(e);
|
|
1023
1024
|
if (!ends) continue;
|
|
1024
1025
|
const [va, vb] = ends;
|
|
1025
|
-
const ka =
|
|
1026
|
-
const kb =
|
|
1027
|
-
|
|
1028
|
-
const
|
|
1026
|
+
const ka = va.key;
|
|
1027
|
+
const kb = vb.key;
|
|
1028
|
+
// Defensive check for edge cases where hasVertex may be overridden/undefined
|
|
1029
|
+
const hasA = typeof g.hasVertex === 'function' ? g.hasVertex(ka) : false;
|
|
1030
|
+
const hasB = typeof g.hasVertex === 'function' ? g.hasVertex(kb) : false;
|
|
1029
1031
|
if (hasA && hasB) {
|
|
1030
|
-
const
|
|
1031
|
-
|
|
1032
|
-
const newEdge = (g as any).createEdge(ka, kb, w, val);
|
|
1033
|
-
(g as any)._addEdge(newEdge);
|
|
1032
|
+
const newEdge = g.createEdge(ka, kb, e.weight, e.value);
|
|
1033
|
+
(g as this & { _addEdge(edge: EO): boolean })._addEdge(newEdge);
|
|
1034
1034
|
}
|
|
1035
1035
|
}
|
|
1036
1036
|
return g;
|
|
@@ -207,8 +207,8 @@ export class DirectedGraph<
|
|
|
207
207
|
* @returns DirectedGraph with all keys added.
|
|
208
208
|
* @remarks Time O(V), Space O(V)
|
|
209
209
|
*/
|
|
210
|
-
static fromKeys<K extends VertexKey>(keys: Iterable<K>): DirectedGraph<K,
|
|
211
|
-
const g: DirectedGraph<K,
|
|
210
|
+
static fromKeys<K extends VertexKey>(keys: Iterable<K>): DirectedGraph<K, undefined, DirectedVertex<K>, DirectedEdge<undefined>> {
|
|
211
|
+
const g: DirectedGraph<K, undefined, DirectedVertex<K>, DirectedEdge<undefined>> = new DirectedGraph<K, undefined>({
|
|
212
212
|
vertexValueInitializer: (k: VertexKey) => k as K
|
|
213
213
|
});
|
|
214
214
|
for (const k of keys) g.addVertex(k);
|
|
@@ -224,8 +224,8 @@ export class DirectedGraph<
|
|
|
224
224
|
*/
|
|
225
225
|
static fromEntries<V>(
|
|
226
226
|
entries: Iterable<[VertexKey, V]>
|
|
227
|
-
): DirectedGraph<V,
|
|
228
|
-
const g: DirectedGraph<V,
|
|
227
|
+
): DirectedGraph<V, undefined, DirectedVertex<V>, DirectedEdge<undefined>> {
|
|
228
|
+
const g: DirectedGraph<V, undefined, DirectedVertex<V>, DirectedEdge<undefined>> = new DirectedGraph<V, undefined>();
|
|
229
229
|
for (const [k, v] of entries) g.addVertex(k, v);
|
|
230
230
|
return g;
|
|
231
231
|
}
|