d-ary-heap 2.1.1

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/index.js ADDED
@@ -0,0 +1,509 @@
1
+ // src/PriorityQueue.ts
2
+ var PriorityQueue = class _PriorityQueue {
3
+ /** Array-based heap storage (complete tree representation) */
4
+ container;
5
+ /** Maps each item's key to its position in the container for O(1) lookup */
6
+ positions;
7
+ /** Number of children per node (arity of the heap) */
8
+ depth;
9
+ /** Comparator determining heap order (min vs max) */
10
+ comparator;
11
+ /** Key extractor for identity-based lookup */
12
+ keyExtractor;
13
+ /**
14
+ * Create a new d-ary heap priority queue.
15
+ *
16
+ * @param options - Configuration options
17
+ * @throws Error if d < 1
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // Min-heap by cost
22
+ * const pq = new PriorityQueue<Item, number>({
23
+ * d: 4,
24
+ * comparator: (a, b) => a.cost < b.cost,
25
+ * keyExtractor: (item) => item.id
26
+ * });
27
+ * ```
28
+ */
29
+ constructor(options) {
30
+ const d = options.d ?? 2;
31
+ if (d < 1) {
32
+ throw new Error("Heap arity (d) must be >= 1");
33
+ }
34
+ this.depth = d;
35
+ this.comparator = options.comparator;
36
+ this.keyExtractor = options.keyExtractor;
37
+ const capacity = options.initialCapacity ?? 0;
38
+ this.container = capacity > 0 ? new Array(capacity) : [];
39
+ if (capacity > 0) this.container.length = 0;
40
+ this.positions = /* @__PURE__ */ new Map();
41
+ }
42
+ /**
43
+ * Create a new priority queue with an initial item already inserted.
44
+ * Equivalent to Rust's `with_first()` constructor.
45
+ *
46
+ * @param options - Configuration options
47
+ * @param firstItem - First item to insert
48
+ * @returns New PriorityQueue with the item already inserted
49
+ */
50
+ static withFirst(options, firstItem) {
51
+ const pq = new _PriorityQueue(options);
52
+ pq.insert(firstItem);
53
+ return pq;
54
+ }
55
+ // ===========================================================================
56
+ // Public API - Query Operations
57
+ // ===========================================================================
58
+ /**
59
+ * Get the number of items in the heap.
60
+ * Time complexity: O(1)
61
+ */
62
+ len() {
63
+ return this.container.length;
64
+ }
65
+ /** Alias for len() - backward compatibility */
66
+ get size() {
67
+ return this.container.length;
68
+ }
69
+ /**
70
+ * Check if the heap is empty.
71
+ * Time complexity: O(1)
72
+ */
73
+ isEmpty() {
74
+ return this.container.length === 0;
75
+ }
76
+ /** Alias for isEmpty() - snake_case for cross-language consistency */
77
+ is_empty() {
78
+ return this.isEmpty();
79
+ }
80
+ /**
81
+ * Get the arity (number of children per node) of the heap.
82
+ * Time complexity: O(1)
83
+ */
84
+ d() {
85
+ return this.depth;
86
+ }
87
+ /**
88
+ * Check if an item with the given key exists in the heap.
89
+ * Time complexity: O(1)
90
+ *
91
+ * @param item - Item to check (uses keyExtractor for identity)
92
+ */
93
+ contains(item) {
94
+ return this.positions.has(this.keyExtractor(item));
95
+ }
96
+ /**
97
+ * Check if an item with the given key exists in the heap.
98
+ * Time complexity: O(1)
99
+ *
100
+ * @param key - Key to check directly
101
+ */
102
+ containsKey(key) {
103
+ return this.positions.has(key);
104
+ }
105
+ /**
106
+ * Get the current position (index) of an item in the heap.
107
+ * Time complexity: O(1)
108
+ *
109
+ * @param item - Item to find (uses keyExtractor for identity)
110
+ * @returns Position index, or undefined if not found
111
+ */
112
+ getPosition(item) {
113
+ return this.positions.get(this.keyExtractor(item));
114
+ }
115
+ /**
116
+ * Get the current position (index) of an item by its key.
117
+ * Time complexity: O(1)
118
+ *
119
+ * @param key - Key to find
120
+ * @returns Position index, or undefined if not found
121
+ */
122
+ getPositionByKey(key) {
123
+ return this.positions.get(key);
124
+ }
125
+ /**
126
+ * Get the highest-priority item without removing it.
127
+ * Time complexity: O(1)
128
+ *
129
+ * @returns The highest-priority item
130
+ * @throws Error if heap is empty
131
+ */
132
+ front() {
133
+ const item = this.container[0];
134
+ if (item === void 0) {
135
+ throw new Error("front() called on empty priority queue");
136
+ }
137
+ return item;
138
+ }
139
+ /**
140
+ * Get the highest-priority item without removing it.
141
+ * Safe alternative to front().
142
+ * Time complexity: O(1)
143
+ *
144
+ * @returns The highest-priority item, or undefined if empty
145
+ */
146
+ peek() {
147
+ return this.container.length > 0 ? this.container[0] : void 0;
148
+ }
149
+ // ===========================================================================
150
+ // Public API - Modification Operations
151
+ // ===========================================================================
152
+ /**
153
+ * Insert a new item into the heap.
154
+ * Time complexity: O(log_d n)
155
+ *
156
+ * @param item - Item to insert
157
+ *
158
+ * @remarks
159
+ * If an item with the same key already exists, behavior is undefined.
160
+ * Use contains() to check first, or use increasePriority()/decreasePriority()
161
+ * to update existing items.
162
+ */
163
+ insert(item) {
164
+ const index = this.container.length;
165
+ this.container.push(item);
166
+ if (index === 0) {
167
+ this.positions.set(this.keyExtractor(item), 0);
168
+ return;
169
+ }
170
+ this.positions.set(this.keyExtractor(item), index);
171
+ this.moveUp(index);
172
+ }
173
+ /**
174
+ * Insert multiple items into the heap.
175
+ * Uses heapify algorithm which is O(n) for bulk insertion vs O(n log n) for individual inserts.
176
+ * Time complexity: O(n) where n is total items after insertion
177
+ *
178
+ * @param items - Array of items to insert
179
+ *
180
+ * @remarks
181
+ * More efficient than calling insert() repeatedly when adding many items at once.
182
+ * If any item has a key that already exists, behavior is undefined.
183
+ */
184
+ insertMany(items) {
185
+ if (items.length === 0) return;
186
+ const keyExtractor = this.keyExtractor;
187
+ const container = this.container;
188
+ const positions = this.positions;
189
+ const startIndex = container.length;
190
+ for (let i = 0; i < items.length; i++) {
191
+ const item = items[i];
192
+ container.push(item);
193
+ positions.set(keyExtractor(item), startIndex + i);
194
+ }
195
+ if (startIndex === 0 && items.length > 1) {
196
+ this.heapify();
197
+ } else {
198
+ for (let i = startIndex; i < container.length; i++) {
199
+ this.moveUp(i);
200
+ }
201
+ }
202
+ }
203
+ /**
204
+ * Build heap property from unordered array.
205
+ * Uses Floyd's algorithm - O(n) time complexity.
206
+ * Called internally by insertMany when starting from empty heap.
207
+ */
208
+ heapify() {
209
+ const n = this.container.length;
210
+ if (n <= 1) return;
211
+ const d = this.depth;
212
+ const lastNonLeaf = (n - 2) / d | 0;
213
+ for (let i = lastNonLeaf; i >= 0; i--) {
214
+ this.moveDown(i);
215
+ }
216
+ }
217
+ /**
218
+ * Increase the priority of an existing item (move toward root).
219
+ * Time complexity: O(log_d n)
220
+ *
221
+ * @param updatedItem - Item with same identity but updated priority
222
+ * @throws Error if item not found
223
+ *
224
+ * @remarks
225
+ * For min-heap: decreasing the priority value increases importance.
226
+ * For max-heap: increasing the priority value increases importance.
227
+ * This method only moves items upward for performance.
228
+ */
229
+ increasePriority(updatedItem) {
230
+ const key = this.keyExtractor(updatedItem);
231
+ const index = this.positions.get(key);
232
+ if (index === void 0) {
233
+ throw new Error("Item not found in priority queue");
234
+ }
235
+ this.container[index] = updatedItem;
236
+ this.moveUp(index);
237
+ }
238
+ /** Alias for increasePriority() - snake_case for cross-language consistency */
239
+ increase_priority(updatedItem) {
240
+ this.increasePriority(updatedItem);
241
+ }
242
+ /**
243
+ * Increase the priority of the item at the given index.
244
+ * Time complexity: O(log_d n)
245
+ *
246
+ * @param index - Index of the item in the heap array
247
+ * @throws Error if index is out of bounds
248
+ *
249
+ * @remarks
250
+ * This is a lower-level method. Prefer increasePriority() with the item itself.
251
+ */
252
+ increasePriorityByIndex(index) {
253
+ if (index < 0 || index >= this.container.length) {
254
+ throw new Error("Index out of bounds");
255
+ }
256
+ this.moveUp(index);
257
+ }
258
+ /** Alias for increasePriorityByIndex() - snake_case for cross-language consistency */
259
+ increase_priority_by_index(index) {
260
+ this.increasePriorityByIndex(index);
261
+ }
262
+ /**
263
+ * Decrease the priority of an existing item (move toward leaves).
264
+ * Time complexity: O(d · log_d n)
265
+ *
266
+ * @param updatedItem - Item with same identity but updated priority
267
+ * @throws Error if item not found
268
+ *
269
+ * @remarks
270
+ * For min-heap: increasing the priority value decreases importance.
271
+ * For max-heap: decreasing the priority value decreases importance.
272
+ * This method checks both directions for robustness.
273
+ */
274
+ decreasePriority(updatedItem) {
275
+ const key = this.keyExtractor(updatedItem);
276
+ const index = this.positions.get(key);
277
+ if (index === void 0) {
278
+ throw new Error("Item not found in priority queue");
279
+ }
280
+ this.container[index] = updatedItem;
281
+ this.moveUp(index);
282
+ this.moveDown(index);
283
+ }
284
+ /** Alias for decreasePriority() - snake_case for cross-language consistency */
285
+ decrease_priority(updatedItem) {
286
+ this.decreasePriority(updatedItem);
287
+ }
288
+ /**
289
+ * Remove and return the highest-priority item.
290
+ * Time complexity: O(d · log_d n)
291
+ *
292
+ * @returns The removed item, or undefined if empty
293
+ */
294
+ pop() {
295
+ const container = this.container;
296
+ const n = container.length;
297
+ if (n === 0) {
298
+ return void 0;
299
+ }
300
+ const keyExtractor = this.keyExtractor;
301
+ const top = container[0];
302
+ this.positions.delete(keyExtractor(top));
303
+ if (n === 1) {
304
+ container.length = 0;
305
+ return top;
306
+ }
307
+ const lastItem = container[n - 1];
308
+ container[0] = lastItem;
309
+ this.positions.set(keyExtractor(lastItem), 0);
310
+ container.length = n - 1;
311
+ this.moveDown(0);
312
+ return top;
313
+ }
314
+ /**
315
+ * Remove and return multiple highest-priority items.
316
+ * More efficient than calling pop() repeatedly.
317
+ * Time complexity: O(count · d · log_d n)
318
+ *
319
+ * @param count - Number of items to remove
320
+ * @returns Array of removed items in priority order
321
+ */
322
+ popMany(count) {
323
+ const result = [];
324
+ const actualCount = count < this.container.length ? count : this.container.length;
325
+ for (let i = 0; i < actualCount; i++) {
326
+ const item = this.pop();
327
+ if (item !== void 0) {
328
+ result.push(item);
329
+ }
330
+ }
331
+ return result;
332
+ }
333
+ /**
334
+ * Clear all items from the heap, optionally changing the arity.
335
+ * Time complexity: O(1) (references cleared, GC handles memory)
336
+ *
337
+ * @param newD - Optional new arity value (must be >= 1 if provided)
338
+ * @throws Error if newD < 1
339
+ */
340
+ clear(newD) {
341
+ this.container.length = 0;
342
+ this.positions.clear();
343
+ if (newD !== void 0) {
344
+ if (newD < 1) {
345
+ throw new Error("Heap arity (d) must be >= 1");
346
+ }
347
+ this.depth = newD;
348
+ }
349
+ }
350
+ /**
351
+ * Get a string representation of the heap contents.
352
+ * Time complexity: O(n)
353
+ *
354
+ * @returns Formatted string showing all items in heap order
355
+ */
356
+ toString() {
357
+ return "{" + this.container.map(String).join(", ") + "}";
358
+ }
359
+ /** Alias for toString() - snake_case for cross-language consistency */
360
+ to_string() {
361
+ return this.toString();
362
+ }
363
+ /**
364
+ * Get all items in heap order (for debugging/iteration).
365
+ * Time complexity: O(n) - creates a copy
366
+ *
367
+ * @returns Copy of internal array
368
+ */
369
+ toArray() {
370
+ return [...this.container];
371
+ }
372
+ /**
373
+ * Iterate over items in heap order (not priority order).
374
+ */
375
+ *[Symbol.iterator]() {
376
+ for (const item of this.container) {
377
+ yield item;
378
+ }
379
+ }
380
+ // ===========================================================================
381
+ // Private Methods - Heap Operations
382
+ // ===========================================================================
383
+ /**
384
+ * Swap two items in the heap and update their position mappings.
385
+ * V8 optimizes simple swap patterns well.
386
+ */
387
+ swap(i, j) {
388
+ const container = this.container;
389
+ const temp = container[i];
390
+ container[i] = container[j];
391
+ container[j] = temp;
392
+ this.positions.set(this.keyExtractor(container[i]), i);
393
+ this.positions.set(this.keyExtractor(container[j]), j);
394
+ }
395
+ /**
396
+ * Find the child with highest priority among all children of node i.
397
+ */
398
+ bestChildPosition(i) {
399
+ const d = this.depth;
400
+ const container = this.container;
401
+ const n = container.length;
402
+ const left = i * d + 1;
403
+ if (left >= n) return left;
404
+ let best = left;
405
+ const right = Math.min((i + 1) * d, n - 1);
406
+ for (let j = left + 1; j <= right; j++) {
407
+ if (this.comparator(container[j], container[best])) {
408
+ best = j;
409
+ }
410
+ }
411
+ return best;
412
+ }
413
+ /**
414
+ * Move an item upward in the heap to restore heap property.
415
+ * Uses simple swap pattern which V8 optimizes well.
416
+ */
417
+ moveUp(i) {
418
+ const d = this.depth;
419
+ const container = this.container;
420
+ while (i > 0) {
421
+ const p = Math.floor((i - 1) / d);
422
+ if (this.comparator(container[i], container[p])) {
423
+ this.swap(i, p);
424
+ i = p;
425
+ } else {
426
+ break;
427
+ }
428
+ }
429
+ }
430
+ /**
431
+ * Move an item downward in the heap to restore heap property.
432
+ */
433
+ moveDown(i) {
434
+ const d = this.depth;
435
+ const container = this.container;
436
+ while (true) {
437
+ const firstChild = i * d + 1;
438
+ if (firstChild >= container.length) break;
439
+ const best = this.bestChildPosition(i);
440
+ if (this.comparator(container[best], container[i])) {
441
+ this.swap(i, best);
442
+ i = best;
443
+ } else {
444
+ break;
445
+ }
446
+ }
447
+ }
448
+ };
449
+
450
+ // src/comparators.ts
451
+ function minBy(keyFn) {
452
+ return (a, b) => keyFn(a) < keyFn(b);
453
+ }
454
+ function maxBy(keyFn) {
455
+ return (a, b) => keyFn(a) > keyFn(b);
456
+ }
457
+ var minNumber = (a, b) => a < b;
458
+ var maxNumber = (a, b) => a > b;
459
+ var minString = (a, b) => a < b;
460
+ var maxString = (a, b) => a > b;
461
+ function reverse(cmp) {
462
+ return (a, b) => cmp(b, a);
463
+ }
464
+ function chain(...comparators) {
465
+ return (a, b) => {
466
+ for (const cmp of comparators) {
467
+ if (cmp(a, b)) return true;
468
+ if (cmp(b, a)) return false;
469
+ }
470
+ return false;
471
+ };
472
+ }
473
+ /**
474
+ * d-ary Heap Priority Queue - TypeScript Implementation
475
+ *
476
+ * A generic d-ary heap (d-heap) priority queue with:
477
+ * - Configurable arity (d): number of children per node
478
+ * - Min-heap or max-heap behavior via comparator functions
479
+ * - O(1) item lookup using Map for efficient priority updates
480
+ * - O(1) access to highest-priority item
481
+ * - O(log_d n) insert and priority increase operations
482
+ * - O(d · log_d n) pop and priority decrease operations
483
+ *
484
+ * @version 2.0.0
485
+ * @license Apache-2.0
486
+ * @copyright 2023-2025 Eric Jacopin
487
+ */
488
+ /**
489
+ * Pre-built comparator factories for common use cases.
490
+ *
491
+ * @module comparators
492
+ * @version 2.0.0
493
+ * @license Apache-2.0
494
+ */
495
+ /**
496
+ * d-ary Heap Priority Queue - TypeScript Implementation
497
+ *
498
+ * A high-performance, generic d-ary heap priority queue with O(1) item lookup.
499
+ *
500
+ * @packageDocumentation
501
+ * @module d-ary-heap
502
+ * @version 2.0.0
503
+ * @license Apache-2.0
504
+ * @copyright 2023-2025 Eric Jacopin
505
+ */
506
+
507
+ export { PriorityQueue, chain, maxBy, maxNumber, maxString, minBy, minNumber, minString, reverse };
508
+ //# sourceMappingURL=index.js.map
509
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/PriorityQueue.ts","../src/comparators.ts"],"names":[],"mappings":";AAqEO,IAAM,aAAA,GAAN,MAAM,cAAA,CAAsC;AAAA;AAAA,EAEzC,SAAA;AAAA;AAAA,EAGA,SAAA;AAAA;AAAA,EAGA,KAAA;AAAA;AAAA,EAGS,UAAA;AAAA;AAAA,EAGA,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBjB,YAAY,OAAA,EAAqC;AAC/C,IAAA,MAAM,CAAA,GAAI,QAAQ,CAAA,IAAK,CAAA;AACvB,IAAA,IAAI,IAAI,CAAA,EAAG;AACT,MAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,IAC/C;AAEA,IAAA,IAAA,CAAK,KAAA,GAAQ,CAAA;AACb,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAC1B,IAAA,IAAA,CAAK,eAAe,OAAA,CAAQ,YAAA;AAG5B,IAAA,MAAM,QAAA,GAAW,QAAQ,eAAA,IAAmB,CAAA;AAC5C,IAAA,IAAA,CAAK,YAAY,QAAA,GAAW,CAAA,GAAI,IAAI,KAAA,CAAS,QAAQ,IAAI,EAAC;AAC1D,IAAA,IAAI,QAAA,GAAW,CAAA,EAAG,IAAA,CAAK,SAAA,CAAU,MAAA,GAAS,CAAA;AAC1C,IAAA,IAAA,CAAK,SAAA,uBAAgB,GAAA,EAAiB;AAAA,EACxC;AAAA;AAAA;AAAA;AAA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AA,GAAI,MAAM,CAAC,CAAA;AAC3C;AAcO,SAAS,MAAY,KAAA,EAAsC;AAChE,EAAA,OAAO,CAAC,CAAA,EAAM,CAAA,KAAS,MAAM,CAAC,CAAA,GAAI,MAAM,CAAC,CAAA;AAC3C;AAMO,IAAM,SAAA,GAAgC,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,GAAI;AAMpD,IAAM,SAAA,GAAgC,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,GAAI;AAMpD,IAAM,SAAA,GAAgC,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,GAAI;AAMpD,IAAM,SAAA,GAAgC,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,GAAI;AAapD,SAAS,QAAW,GAAA,EAAmC;AAC5D,EAAA,OAAO,CAAC,CAAA,EAAM,CAAA,KAAS,GAAA,CAAI,GAAG,CAAC,CAAA;AACjC;AAkBO,SAAS,SAAY,WAAA,EAA6C;AACvE,EAAA,OAAO,CAAC,GAAM,CAAA,KAAS;AACrB,IAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,MAAA,IAAI,GAAA,CAAI,CAAA,EAAG,CAAC,CAAA,EAAG,OAAO,IAAA;AACtB,MAAA,IAAI,GAAA,CAAI,CAAA,EAAG,CAAC,CAAA,EAAG,OAAO,KAAA;AAAA,IACxB;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF","file":"index.js","sourcesContent":["/**\r\n * d-ary Heap Priority Queue - TypeScript Implementation\r\n *\r\n * A generic d-ary heap (d-heap) priority queue with:\r\n * - Configurable arity (d): number of children per node\r\n * - Min-heap or max-heap behavior via comparator functions\r\n * - O(1) item lookup using Map for efficient priority updates\r\n * - O(1) access to highest-priority item\r\n * - O(log_d n) insert and priority increase operations\r\n * - O(d · log_d n) pop and priority decrease operations\r\n *\r\n * @version 2.0.0\r\n * @license Apache-2.0\r\n * @copyright 2023-2025 Eric Jacopin\r\n */\r\n\r\n/** Type alias for position indices (cross-language consistency) */\r\nexport type Position = number;\r\n\r\n/**\r\n * Comparator function type for priority comparison.\r\n * Returns true if `a` has higher priority than `b`.\r\n */\r\nexport type Comparator<T> = (a: T, b: T) => boolean;\r\n\r\n/**\r\n * Key extractor function type for identity-based lookup.\r\n * Must return a value that can be used as a Map key (string or number recommended).\r\n */\r\nexport type KeyExtractor<T, K> = (item: T) => K;\r\n\r\n/**\r\n * Configuration options for PriorityQueue construction.\r\n */\r\nexport interface PriorityQueueOptions<T, K> {\r\n /** Number of children per node (arity). Must be >= 1. Default: 2 */\r\n d?: number;\r\n /** Comparator function. Returns true if first arg has higher priority. */\r\n comparator: Comparator<T>;\r\n /** Key extractor for identity-based lookup. Required for decrease/increase priority. */\r\n keyExtractor: KeyExtractor<T, K>;\r\n /** Initial capacity hint for pre-allocation */\r\n initialCapacity?: number;\r\n}\r\n\r\n/**\r\n * Generic d-ary heap priority queue with O(1) lookup.\r\n *\r\n * A d-ary heap is a tree structure where:\r\n * - Each node has at most d children\r\n * - The root contains the highest-priority item\r\n * - Each parent has higher priority than all its children\r\n * - The tree is complete (filled left-to-right, level by level)\r\n *\r\n * This implementation uses an array-based representation with O(1) item lookup\r\n * via a Map that tracks each item's position in the heap.\r\n *\r\n * ## Time Complexities\r\n * - front(), peek(): O(1)\r\n * - insert(): O(log_d n)\r\n * - pop(): O(d · log_d n)\r\n * - increasePriority(): O(log_d n)\r\n * - decreasePriority(): O(d · log_d n)\r\n * - contains(): O(1)\r\n * - len(), isEmpty(), d(): O(1)\r\n *\r\n * @typeParam T - Item type stored in the queue\r\n * @typeParam K - Key type for identity lookup (typically string or number)\r\n */\r\nexport class PriorityQueue<T, K = string | number> {\r\n /** Array-based heap storage (complete tree representation) */\r\n private container: T[];\r\n\r\n /** Maps each item's key to its position in the container for O(1) lookup */\r\n private positions: Map<K, Position>;\r\n\r\n /** Number of children per node (arity of the heap) */\r\n private depth: number;\r\n\r\n /** Comparator determining heap order (min vs max) */\r\n private readonly comparator: Comparator<T>;\r\n\r\n /** Key extractor for identity-based lookup */\r\n private readonly keyExtractor: KeyExtractor<T, K>;\r\n\r\n /**\r\n * Create a new d-ary heap priority queue.\r\n *\r\n * @param options - Configuration options\r\n * @throws Error if d < 1\r\n *\r\n * @example\r\n * ```typescript\r\n * // Min-heap by cost\r\n * const pq = new PriorityQueue<Item, number>({\r\n * d: 4,\r\n * comparator: (a, b) => a.cost < b.cost,\r\n * keyExtractor: (item) => item.id\r\n * });\r\n * ```\r\n */\r\n constructor(options: PriorityQueueOptions<T, K>) {\r\n const d = options.d ?? 2;\r\n if (d < 1) {\r\n throw new Error('Heap arity (d) must be >= 1');\r\n }\r\n\r\n this.depth = d;\r\n this.comparator = options.comparator;\r\n this.keyExtractor = options.keyExtractor;\r\n\r\n // Pre-allocate if capacity hint provided\r\n const capacity = options.initialCapacity ?? 0;\r\n this.container = capacity > 0 ? new Array<T>(capacity) : [];\r\n if (capacity > 0) this.container.length = 0; // Reset length but keep capacity\r\n this.positions = new Map<K, Position>();\r\n }\r\n\r\n /**\r\n * Create a new priority queue with an initial item already inserted.\r\n * Equivalent to Rust's `with_first()` constructor.\r\n *\r\n * @param options - Configuration options\r\n * @param firstItem - First item to insert\r\n * @returns New PriorityQueue with the item already inserted\r\n */\r\n static withFirst<T, K>(\r\n options: PriorityQueueOptions<T, K>,\r\n firstItem: T\r\n ): PriorityQueue<T, K> {\r\n const pq = new PriorityQueue<T, K>(options);\r\n pq.insert(firstItem);\r\n return pq;\r\n }\r\n\r\n // ===========================================================================\r\n // Public API - Query Operations\r\n // ===========================================================================\r\n\r\n /**\r\n * Get the number of items in the heap.\r\n * Time complexity: O(1)\r\n */\r\n len(): number {\r\n return this.container.length;\r\n }\r\n\r\n /** Alias for len() - backward compatibility */\r\n get size(): number {\r\n return this.container.length;\r\n }\r\n\r\n /**\r\n * Check if the heap is empty.\r\n * Time complexity: O(1)\r\n */\r\n isEmpty(): boolean {\r\n return this.container.length === 0;\r\n }\r\n\r\n /** Alias for isEmpty() - snake_case for cross-language consistency */\r\n is_empty(): boolean {\r\n return this.isEmpty();\r\n }\r\n\r\n /**\r\n * Get the arity (number of children per node) of the heap.\r\n * Time complexity: O(1)\r\n */\r\n d(): number {\r\n return this.depth;\r\n }\r\n\r\n /**\r\n * Check if an item with the given key exists in the heap.\r\n * Time complexity: O(1)\r\n *\r\n * @param item - Item to check (uses keyExtractor for identity)\r\n */\r\n contains(item: T): boolean {\r\n return this.positions.has(this.keyExtractor(item));\r\n }\r\n\r\n /**\r\n * Check if an item with the given key exists in the heap.\r\n * Time complexity: O(1)\r\n *\r\n * @param key - Key to check directly\r\n */\r\n containsKey(key: K): boolean {\r\n return this.positions.has(key);\r\n }\r\n\r\n /**\r\n * Get the current position (index) of an item in the heap.\r\n * Time complexity: O(1)\r\n *\r\n * @param item - Item to find (uses keyExtractor for identity)\r\n * @returns Position index, or undefined if not found\r\n */\r\n getPosition(item: T): Position | undefined {\r\n return this.positions.get(this.keyExtractor(item));\r\n }\r\n\r\n /**\r\n * Get the current position (index) of an item by its key.\r\n * Time complexity: O(1)\r\n *\r\n * @param key - Key to find\r\n * @returns Position index, or undefined if not found\r\n */\r\n getPositionByKey(key: K): Position | undefined {\r\n return this.positions.get(key);\r\n }\r\n\r\n /**\r\n * Get the highest-priority item without removing it.\r\n * Time complexity: O(1)\r\n *\r\n * @returns The highest-priority item\r\n * @throws Error if heap is empty\r\n */\r\n front(): T {\r\n const item = this.container[0];\r\n if (item === undefined) {\r\n throw new Error('front() called on empty priority queue');\r\n }\r\n return item;\r\n }\r\n\r\n /**\r\n * Get the highest-priority item without removing it.\r\n * Safe alternative to front().\r\n * Time complexity: O(1)\r\n *\r\n * @returns The highest-priority item, or undefined if empty\r\n */\r\n peek(): T | undefined {\r\n return this.container.length > 0 ? this.container[0] : undefined;\r\n }\r\n\r\n // ===========================================================================\r\n // Public API - Modification Operations\r\n // ===========================================================================\r\n\r\n /**\r\n * Insert a new item into the heap.\r\n * Time complexity: O(log_d n)\r\n *\r\n * @param item - Item to insert\r\n *\r\n * @remarks\r\n * If an item with the same key already exists, behavior is undefined.\r\n * Use contains() to check first, or use increasePriority()/decreasePriority()\r\n * to update existing items.\r\n */\r\n insert(item: T): void {\r\n const index = this.container.length;\r\n this.container.push(item);\r\n\r\n // Fast path: first item doesn't need sift-up\r\n if (index === 0) {\r\n this.positions.set(this.keyExtractor(item), 0);\r\n return;\r\n }\r\n\r\n this.positions.set(this.keyExtractor(item), index);\r\n this.moveUp(index);\r\n }\r\n\r\n /**\r\n * Insert multiple items into the heap.\r\n * Uses heapify algorithm which is O(n) for bulk insertion vs O(n log n) for individual inserts.\r\n * Time complexity: O(n) where n is total items after insertion\r\n *\r\n * @param items - Array of items to insert\r\n *\r\n * @remarks\r\n * More efficient than calling insert() repeatedly when adding many items at once.\r\n * If any item has a key that already exists, behavior is undefined.\r\n */\r\n insertMany(items: T[]): void {\r\n if (items.length === 0) return;\r\n\r\n const keyExtractor = this.keyExtractor;\r\n const container = this.container;\r\n const positions = this.positions;\r\n const startIndex = container.length;\r\n\r\n // Add all items to container and positions map\r\n for (let i = 0; i < items.length; i++) {\r\n const item = items[i]!;\r\n container.push(item);\r\n positions.set(keyExtractor(item), startIndex + i);\r\n }\r\n\r\n // If this was an empty heap, use heapify (O(n)) instead of n insertions (O(n log n))\r\n if (startIndex === 0 && items.length > 1) {\r\n this.heapify();\r\n } else {\r\n // Otherwise, sift up each new item\r\n for (let i = startIndex; i < container.length; i++) {\r\n this.moveUp(i);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Build heap property from unordered array.\r\n * Uses Floyd's algorithm - O(n) time complexity.\r\n * Called internally by insertMany when starting from empty heap.\r\n */\r\n private heapify(): void {\r\n const n = this.container.length;\r\n if (n <= 1) return;\r\n\r\n const d = this.depth;\r\n // Start from last non-leaf node and sift down each\r\n // Last non-leaf is parent of last element: floor((n-2)/d)\r\n const lastNonLeaf = ((n - 2) / d) | 0;\r\n\r\n for (let i = lastNonLeaf; i >= 0; i--) {\r\n this.moveDown(i);\r\n }\r\n }\r\n\r\n /**\r\n * Increase the priority of an existing item (move toward root).\r\n * Time complexity: O(log_d n)\r\n *\r\n * @param updatedItem - Item with same identity but updated priority\r\n * @throws Error if item not found\r\n *\r\n * @remarks\r\n * For min-heap: decreasing the priority value increases importance.\r\n * For max-heap: increasing the priority value increases importance.\r\n * This method only moves items upward for performance.\r\n */\r\n increasePriority(updatedItem: T): void {\r\n const key = this.keyExtractor(updatedItem);\r\n const index = this.positions.get(key);\r\n\r\n if (index === undefined) {\r\n throw new Error('Item not found in priority queue');\r\n }\r\n\r\n this.container[index] = updatedItem;\r\n this.moveUp(index);\r\n }\r\n\r\n /** Alias for increasePriority() - snake_case for cross-language consistency */\r\n increase_priority(updatedItem: T): void {\r\n this.increasePriority(updatedItem);\r\n }\r\n\r\n /**\r\n * Increase the priority of the item at the given index.\r\n * Time complexity: O(log_d n)\r\n *\r\n * @param index - Index of the item in the heap array\r\n * @throws Error if index is out of bounds\r\n *\r\n * @remarks\r\n * This is a lower-level method. Prefer increasePriority() with the item itself.\r\n */\r\n increasePriorityByIndex(index: number): void {\r\n if (index < 0 || index >= this.container.length) {\r\n throw new Error('Index out of bounds');\r\n }\r\n this.moveUp(index);\r\n }\r\n\r\n /** Alias for increasePriorityByIndex() - snake_case for cross-language consistency */\r\n increase_priority_by_index(index: number): void {\r\n this.increasePriorityByIndex(index);\r\n }\r\n\r\n /**\r\n * Decrease the priority of an existing item (move toward leaves).\r\n * Time complexity: O(d · log_d n)\r\n *\r\n * @param updatedItem - Item with same identity but updated priority\r\n * @throws Error if item not found\r\n *\r\n * @remarks\r\n * For min-heap: increasing the priority value decreases importance.\r\n * For max-heap: decreasing the priority value decreases importance.\r\n * This method checks both directions for robustness.\r\n */\r\n decreasePriority(updatedItem: T): void {\r\n const key = this.keyExtractor(updatedItem);\r\n const index = this.positions.get(key);\r\n\r\n if (index === undefined) {\r\n throw new Error('Item not found in priority queue');\r\n }\r\n\r\n this.container[index] = updatedItem;\r\n // Check both directions since we don't know if priority actually decreased\r\n this.moveUp(index);\r\n this.moveDown(index);\r\n }\r\n\r\n /** Alias for decreasePriority() - snake_case for cross-language consistency */\r\n decrease_priority(updatedItem: T): void {\r\n this.decreasePriority(updatedItem);\r\n }\r\n\r\n /**\r\n * Remove and return the highest-priority item.\r\n * Time complexity: O(d · log_d n)\r\n *\r\n * @returns The removed item, or undefined if empty\r\n */\r\n pop(): T | undefined {\r\n const container = this.container;\r\n const n = container.length;\r\n\r\n if (n === 0) {\r\n return undefined;\r\n }\r\n\r\n const keyExtractor = this.keyExtractor;\r\n const top = container[0]!;\r\n this.positions.delete(keyExtractor(top));\r\n\r\n if (n === 1) {\r\n container.length = 0;\r\n return top;\r\n }\r\n\r\n // Move last item to root and sift down\r\n const lastItem = container[n - 1]!;\r\n container[0] = lastItem;\r\n this.positions.set(keyExtractor(lastItem), 0);\r\n container.length = n - 1;\r\n\r\n this.moveDown(0);\r\n\r\n return top;\r\n }\r\n\r\n /**\r\n * Remove and return multiple highest-priority items.\r\n * More efficient than calling pop() repeatedly.\r\n * Time complexity: O(count · d · log_d n)\r\n *\r\n * @param count - Number of items to remove\r\n * @returns Array of removed items in priority order\r\n */\r\n popMany(count: number): T[] {\r\n const result: T[] = [];\r\n const actualCount = count < this.container.length ? count : this.container.length;\r\n\r\n for (let i = 0; i < actualCount; i++) {\r\n const item = this.pop();\r\n if (item !== undefined) {\r\n result.push(item);\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Clear all items from the heap, optionally changing the arity.\r\n * Time complexity: O(1) (references cleared, GC handles memory)\r\n *\r\n * @param newD - Optional new arity value (must be >= 1 if provided)\r\n * @throws Error if newD < 1\r\n */\r\n clear(newD?: number): void {\r\n this.container.length = 0;\r\n this.positions.clear();\r\n\r\n if (newD !== undefined) {\r\n if (newD < 1) {\r\n throw new Error('Heap arity (d) must be >= 1');\r\n }\r\n this.depth = newD;\r\n }\r\n }\r\n\r\n /**\r\n * Get a string representation of the heap contents.\r\n * Time complexity: O(n)\r\n *\r\n * @returns Formatted string showing all items in heap order\r\n */\r\n toString(): string {\r\n return '{' + this.container.map(String).join(', ') + '}';\r\n }\r\n\r\n /** Alias for toString() - snake_case for cross-language consistency */\r\n to_string(): string {\r\n return this.toString();\r\n }\r\n\r\n /**\r\n * Get all items in heap order (for debugging/iteration).\r\n * Time complexity: O(n) - creates a copy\r\n *\r\n * @returns Copy of internal array\r\n */\r\n toArray(): T[] {\r\n return [...this.container];\r\n }\r\n\r\n /**\r\n * Iterate over items in heap order (not priority order).\r\n */\r\n *[Symbol.iterator](): Iterator<T> {\r\n for (const item of this.container) {\r\n yield item;\r\n }\r\n }\r\n\r\n // ===========================================================================\r\n // Private Methods - Heap Operations\r\n // ===========================================================================\r\n\r\n /**\r\n * Swap two items in the heap and update their position mappings.\r\n * V8 optimizes simple swap patterns well.\r\n */\r\n private swap(i: number, j: number): void {\r\n const container = this.container;\r\n const temp = container[i]!;\r\n container[i] = container[j]!;\r\n container[j] = temp;\r\n\r\n // Update positions\r\n this.positions.set(this.keyExtractor(container[i]!), i);\r\n this.positions.set(this.keyExtractor(container[j]!), j);\r\n }\r\n\r\n /**\r\n * Find the child with highest priority among all children of node i.\r\n */\r\n private bestChildPosition(i: number): number {\r\n const d = this.depth;\r\n const container = this.container;\r\n const n = container.length;\r\n const left = i * d + 1;\r\n\r\n if (left >= n) return left;\r\n\r\n let best = left;\r\n const right = Math.min((i + 1) * d, n - 1);\r\n\r\n for (let j = left + 1; j <= right; j++) {\r\n if (this.comparator(container[j]!, container[best]!)) {\r\n best = j;\r\n }\r\n }\r\n\r\n return best;\r\n }\r\n\r\n /**\r\n * Move an item upward in the heap to restore heap property.\r\n * Uses simple swap pattern which V8 optimizes well.\r\n */\r\n private moveUp(i: number): void {\r\n const d = this.depth;\r\n const container = this.container;\r\n\r\n while (i > 0) {\r\n const p = Math.floor((i - 1) / d);\r\n if (this.comparator(container[i]!, container[p]!)) {\r\n this.swap(i, p);\r\n i = p;\r\n } else {\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Move an item downward in the heap to restore heap property.\r\n */\r\n private moveDown(i: number): void {\r\n const d = this.depth;\r\n const container = this.container;\r\n\r\n while (true) {\r\n const firstChild = i * d + 1;\r\n if (firstChild >= container.length) break;\r\n\r\n const best = this.bestChildPosition(i);\r\n if (this.comparator(container[best]!, container[i]!)) {\r\n this.swap(i, best);\r\n i = best;\r\n } else {\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n","/**\r\n * Pre-built comparator factories for common use cases.\r\n *\r\n * @module comparators\r\n * @version 2.0.0\r\n * @license Apache-2.0\r\n */\r\n\r\nimport type { Comparator } from './PriorityQueue';\r\n\r\n/**\r\n * Create a min-heap comparator using a key extractor.\r\n * Lower key values have higher priority (appear closer to root).\r\n *\r\n * @param keyFn - Function to extract the comparable key from an item\r\n * @returns Comparator function for min-heap behavior\r\n *\r\n * @example\r\n * ```typescript\r\n * const minByCost = minBy<Item, number>(item => item.cost);\r\n * ```\r\n */\r\nexport function minBy<T, K>(keyFn: (item: T) => K): Comparator<T> {\r\n return (a: T, b: T) => keyFn(a) < keyFn(b);\r\n}\r\n\r\n/**\r\n * Create a max-heap comparator using a key extractor.\r\n * Higher key values have higher priority (appear closer to root).\r\n *\r\n * @param keyFn - Function to extract the comparable key from an item\r\n * @returns Comparator function for max-heap behavior\r\n *\r\n * @example\r\n * ```typescript\r\n * const maxByCost = maxBy<Item, number>(item => item.cost);\r\n * ```\r\n */\r\nexport function maxBy<T, K>(keyFn: (item: T) => K): Comparator<T> {\r\n return (a: T, b: T) => keyFn(a) > keyFn(b);\r\n}\r\n\r\n/**\r\n * Min-heap comparator for primitive number values.\r\n * Lower numbers have higher priority.\r\n */\r\nexport const minNumber: Comparator<number> = (a, b) => a < b;\r\n\r\n/**\r\n * Max-heap comparator for primitive number values.\r\n * Higher numbers have higher priority.\r\n */\r\nexport const maxNumber: Comparator<number> = (a, b) => a > b;\r\n\r\n/**\r\n * Min-heap comparator for primitive string values.\r\n * Lexicographically smaller strings have higher priority.\r\n */\r\nexport const minString: Comparator<string> = (a, b) => a < b;\r\n\r\n/**\r\n * Max-heap comparator for primitive string values.\r\n * Lexicographically larger strings have higher priority.\r\n */\r\nexport const maxString: Comparator<string> = (a, b) => a > b;\r\n\r\n/**\r\n * Create a comparator that reverses another comparator.\r\n *\r\n * @param cmp - Original comparator to reverse\r\n * @returns Reversed comparator\r\n *\r\n * @example\r\n * ```typescript\r\n * const maxByCost = reverse(minBy<Item, number>(item => item.cost));\r\n * ```\r\n */\r\nexport function reverse<T>(cmp: Comparator<T>): Comparator<T> {\r\n return (a: T, b: T) => cmp(b, a);\r\n}\r\n\r\n/**\r\n * Create a comparator that compares by multiple keys in order.\r\n * Falls back to subsequent comparators when items are equal.\r\n *\r\n * @param comparators - Array of comparators to apply in order\r\n * @returns Combined comparator\r\n *\r\n * @example\r\n * ```typescript\r\n * // Sort by priority first, then by timestamp\r\n * const cmp = chain(\r\n * minBy<Task, number>(t => t.priority),\r\n * minBy<Task, number>(t => t.timestamp)\r\n * );\r\n * ```\r\n */\r\nexport function chain<T>(...comparators: Comparator<T>[]): Comparator<T> {\r\n return (a: T, b: T) => {\r\n for (const cmp of comparators) {\r\n if (cmp(a, b)) return true;\r\n if (cmp(b, a)) return false;\r\n }\r\n return false;\r\n };\r\n}\r\n"]}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "type": "module",
3
+ "name": "d-ary-heap",
4
+ "version": "2.1.1",
5
+ "description": "High-performance d-ary heap priority queue with O(1) item lookup, configurable arity, and min/max heap support",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "test": "vitest run",
23
+ "test:watch": "vitest",
24
+ "test:coverage": "vitest run --coverage",
25
+ "lint": "eslint src --ext .ts",
26
+ "typecheck": "tsc --noEmit",
27
+ "prepublishOnly": "npm run build"
28
+ },
29
+ "keywords": [
30
+ "priority-queue",
31
+ "heap",
32
+ "d-ary-heap",
33
+ "d-heap",
34
+ "min-heap",
35
+ "max-heap",
36
+ "data-structure",
37
+ "algorithm",
38
+ "dijkstra",
39
+ "typescript"
40
+ ],
41
+ "author": "Eric Jacopin",
42
+ "license": "Apache-2.0",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/PCfVW/d-Heap-priority-queue"
46
+ },
47
+ "devDependencies": {
48
+ "@eslint/js": "^9.39.2",
49
+ "@types/node": "^20.10.0",
50
+ "@typescript-eslint/eslint-plugin": "^8.50.0",
51
+ "@typescript-eslint/parser": "^8.50.0",
52
+ "eslint": "^9.39.2",
53
+ "tsup": "^8.0.0",
54
+ "typescript": "^5.3.0",
55
+ "vitest": "^1.0.0"
56
+ },
57
+ "engines": {
58
+ "node": ">=18.0.0"
59
+ }
60
+ }