priority-queue-typed 2.4.4 → 2.4.5

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.
Files changed (45) hide show
  1. package/dist/cjs/index.cjs +57 -35
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +56 -34
  4. package/dist/cjs-legacy/index.cjs.map +1 -1
  5. package/dist/esm/index.mjs +57 -36
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +56 -35
  8. package/dist/esm-legacy/index.mjs.map +1 -1
  9. package/dist/types/common/error.d.ts +23 -0
  10. package/dist/types/common/index.d.ts +1 -0
  11. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +10 -0
  12. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +7 -1
  13. package/dist/types/data-structures/graph/abstract-graph.d.ts +44 -0
  14. package/dist/types/data-structures/graph/directed-graph.d.ts +1 -0
  15. package/dist/types/data-structures/graph/undirected-graph.d.ts +14 -0
  16. package/dist/types/data-structures/queue/deque.d.ts +41 -1
  17. package/dist/types/types/data-structures/queue/deque.d.ts +6 -0
  18. package/dist/umd/priority-queue-typed.js +54 -32
  19. package/dist/umd/priority-queue-typed.js.map +1 -1
  20. package/dist/umd/priority-queue-typed.min.js +1 -1
  21. package/dist/umd/priority-queue-typed.min.js.map +1 -1
  22. package/package.json +2 -2
  23. package/src/common/error.ts +60 -0
  24. package/src/common/index.ts +2 -0
  25. package/src/data-structures/base/iterable-element-base.ts +3 -2
  26. package/src/data-structures/binary-tree/binary-indexed-tree.ts +6 -5
  27. package/src/data-structures/binary-tree/binary-tree.ts +113 -42
  28. package/src/data-structures/binary-tree/bst.ts +11 -3
  29. package/src/data-structures/binary-tree/red-black-tree.ts +20 -0
  30. package/src/data-structures/binary-tree/tree-map.ts +8 -7
  31. package/src/data-structures/binary-tree/tree-multi-map.ts +4 -4
  32. package/src/data-structures/binary-tree/tree-multi-set.ts +5 -4
  33. package/src/data-structures/binary-tree/tree-set.ts +7 -6
  34. package/src/data-structures/graph/abstract-graph.ts +106 -1
  35. package/src/data-structures/graph/directed-graph.ts +4 -0
  36. package/src/data-structures/graph/undirected-graph.ts +95 -0
  37. package/src/data-structures/hash/hash-map.ts +13 -2
  38. package/src/data-structures/heap/heap.ts +4 -3
  39. package/src/data-structures/heap/max-heap.ts +2 -3
  40. package/src/data-structures/matrix/matrix.ts +9 -10
  41. package/src/data-structures/priority-queue/max-priority-queue.ts +2 -3
  42. package/src/data-structures/queue/deque.ts +71 -3
  43. package/src/data-structures/trie/trie.ts +2 -1
  44. package/src/types/data-structures/queue/deque.ts +7 -0
  45. package/src/utils/utils.ts +4 -2
@@ -337,4 +337,48 @@ export declare abstract class AbstractGraph<V = any, E = any, VO extends Abstrac
337
337
  * @remarks Time O(1), Space O(1)
338
338
  */
339
339
  protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey;
340
+ /**
341
+ * The edge connector string used in visual output.
342
+ * Override in subclasses (e.g., '--' for undirected, '->' for directed).
343
+ */
344
+ protected get _edgeConnector(): string;
345
+ /**
346
+ * Generate a text-based visual representation of the graph.
347
+ *
348
+ * **Adjacency list format:**
349
+ * ```
350
+ * Graph (5 vertices, 6 edges):
351
+ * A -> B (1), C (2)
352
+ * B -> D (3)
353
+ * C -> (no outgoing edges)
354
+ * D -> A (1)
355
+ * E (isolated)
356
+ * ```
357
+ *
358
+ * @param options - Optional display settings.
359
+ * @param options.showWeight - Whether to show edge weights (default: true).
360
+ * @returns The visual string.
361
+ */
362
+ toVisual(options?: {
363
+ showWeight?: boolean;
364
+ }): string;
365
+ /**
366
+ * Generate DOT language representation for Graphviz.
367
+ *
368
+ * @param options - Optional display settings.
369
+ * @param options.name - Graph name (default: 'G').
370
+ * @param options.showWeight - Whether to label edges with weight (default: true).
371
+ * @returns DOT format string.
372
+ */
373
+ toDot(options?: {
374
+ name?: string;
375
+ showWeight?: boolean;
376
+ }): string;
377
+ /**
378
+ * Print the graph to console.
379
+ * @param options - Display settings passed to `toVisual`.
380
+ */
381
+ print(options?: {
382
+ showWeight?: boolean;
383
+ }): void;
340
384
  }
@@ -157,6 +157,7 @@ export declare class DirectedGraph<V = any, E = any, VO extends DirectedVertex<V
157
157
  * @remarks Time O(1), Space O(1)
158
158
  */
159
159
  constructor(options?: Partial<GraphOptions<V>>);
160
+ protected get _edgeConnector(): string;
160
161
  protected _outEdgeMap: Map<VO, EO[]>;
161
162
  get outEdgeMap(): Map<VO, EO[]>;
162
163
  set outEdgeMap(v: Map<VO, EO[]>);
@@ -313,6 +313,20 @@ export declare class UndirectedGraph<V = any, E = any, VO extends UndirectedVert
313
313
  bridges: EO[];
314
314
  cutVertices: VO[];
315
315
  };
316
+ /**
317
+ * Find biconnected components using edge-stack Tarjan variant.
318
+ * A biconnected component is a maximal biconnected subgraph.
319
+ * @returns Array of edge arrays, each representing a biconnected component.
320
+ * @remarks Time O(V + E), Space O(V + E)
321
+ */
322
+ getBiconnectedComponents(): EO[][];
323
+ /**
324
+ * Detect whether the graph contains a cycle.
325
+ * Uses DFS with parent tracking.
326
+ * @returns `true` if a cycle exists, `false` otherwise.
327
+ * @remarks Time O(V + E), Space O(V)
328
+ */
329
+ hasCycle(): boolean;
316
330
  /**
317
331
  * Get bridges discovered by `tarjan()`.
318
332
  * @returns Array of edges that are bridges.
@@ -143,7 +143,10 @@ export declare class Deque<E = any, R = any> extends LinearBase<E, R> {
143
143
  * @param [options] - Options such as bucketSize, toElementFn, and maxLen.
144
144
  * @returns New Deque instance.
145
145
  */
146
- constructor(elements?: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>, options?: DequeOptions<E, R>);
146
+ constructor(elements?: IterableWithSizeOrLength<E>, options?: DequeOptions<E, R>);
147
+ constructor(elements: IterableWithSizeOrLength<R>, options: DequeOptions<E, R> & {
148
+ toElementFn: (rawElement: R) => E;
149
+ });
147
150
  protected _bucketSize: number;
148
151
  /**
149
152
  * Get the current bucket size.
@@ -151,6 +154,26 @@ export declare class Deque<E = any, R = any> extends LinearBase<E, R> {
151
154
  * @returns Bucket capacity per bucket.
152
155
  */
153
156
  get bucketSize(): number;
157
+ protected _autoCompactRatio: number;
158
+ /**
159
+ * Get the auto-compaction ratio.
160
+ * When `elements / (bucketCount * bucketSize)` drops below this ratio after
161
+ * enough shift/pop operations, the deque auto-compacts.
162
+ * @remarks Time O(1), Space O(1)
163
+ * @returns Current ratio threshold. 0 means auto-compact is disabled.
164
+ */
165
+ get autoCompactRatio(): number;
166
+ /**
167
+ * Set the auto-compaction ratio.
168
+ * @remarks Time O(1), Space O(1)
169
+ * @param value - Ratio in [0,1]. 0 disables auto-compact.
170
+ */
171
+ set autoCompactRatio(value: number);
172
+ /**
173
+ * Counter for shift/pop operations since last compaction check.
174
+ * Only checks ratio every `_bucketSize` operations to minimize overhead.
175
+ */
176
+ protected _compactCounter: number;
154
177
  protected _bucketFirst: number;
155
178
  /**
156
179
  * Get the index of the first bucket in use.
@@ -369,6 +392,23 @@ export declare class Deque<E = any, R = any> extends LinearBase<E, R> {
369
392
  * @remarks Time O(N), Space O(1)
370
393
  * @returns void
371
394
  */
395
+ /**
396
+ * (Protected) Trigger auto-compaction if space utilization drops below threshold.
397
+ * Only checks every `_bucketSize` operations to minimize hot-path overhead.
398
+ * Uses element-based ratio: `elements / (bucketCount * bucketSize)`.
399
+ */
400
+ protected _autoCompact(): void;
401
+ /**
402
+ * Compact the deque by removing unused buckets.
403
+ * @remarks Time O(N), Space O(1)
404
+ * @returns True if compaction was performed (bucket count reduced).
405
+ */
406
+ /**
407
+ * Compact the deque by removing unused buckets.
408
+ * @remarks Time O(N), Space O(1)
409
+ * @returns True if compaction was performed (bucket count reduced).
410
+ */
411
+ compact(): boolean;
372
412
  shrinkToFit(): void;
373
413
  /**
374
414
  * Deep clone this deque, preserving options.
@@ -1,4 +1,10 @@
1
1
  import { LinearBaseOptions } from '../base';
2
2
  export type DequeOptions<E, R> = {
3
3
  bucketSize?: number;
4
+ /**
5
+ * When the ratio of used buckets to total buckets falls below this threshold
6
+ * after a shift/pop, auto-compact is triggered. Set to 0 to disable.
7
+ * Default: 0.5 (compact when less than half the buckets are in use).
8
+ */
9
+ autoCompactRatio?: number;
4
10
  } & LinearBaseOptions<E, R>;
@@ -24,6 +24,7 @@ var priorityQueueTyped = (() => {
24
24
  var src_exports = {};
25
25
  __export(src_exports, {
26
26
  DFSOperation: () => DFSOperation,
27
+ ERR: () => ERR,
27
28
  FibonacciHeap: () => FibonacciHeap,
28
29
  FibonacciHeapNode: () => FibonacciHeapNode,
29
30
  Heap: () => Heap,
@@ -35,6 +36,52 @@ var priorityQueueTyped = (() => {
35
36
  Range: () => Range
36
37
  });
37
38
 
39
+ // src/common/error.ts
40
+ var ERR = {
41
+ // Range / index
42
+ indexOutOfRange: (index, min, max, ctx) => `${ctx ? ctx + ": " : ""}Index ${index} is out of range [${min}, ${max}].`,
43
+ invalidIndex: (ctx) => `${ctx ? ctx + ": " : ""}Index must be an integer.`,
44
+ // Type / argument
45
+ invalidArgument: (reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`,
46
+ comparatorRequired: (ctx) => `${ctx ? ctx + ": " : ""}Comparator is required for non-number/non-string/non-Date keys.`,
47
+ invalidKey: (reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`,
48
+ notAFunction: (name, ctx) => `${ctx ? ctx + ": " : ""}${name} must be a function.`,
49
+ invalidEntry: (ctx) => `${ctx ? ctx + ": " : ""}Each entry must be a [key, value] tuple.`,
50
+ invalidNaN: (ctx) => `${ctx ? ctx + ": " : ""}NaN is not a valid key.`,
51
+ invalidDate: (ctx) => `${ctx ? ctx + ": " : ""}Invalid Date key.`,
52
+ reduceEmpty: (ctx) => `${ctx ? ctx + ": " : ""}Reduce of empty structure with no initial value.`,
53
+ callbackReturnType: (expected, got, ctx) => `${ctx ? ctx + ": " : ""}Callback must return ${expected}; got ${got}.`,
54
+ // State / operation
55
+ invalidOperation: (reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`,
56
+ // Matrix
57
+ matrixDimensionMismatch: (op) => `Matrix: Dimensions must be compatible for ${op}.`,
58
+ matrixSingular: () => "Matrix: Singular matrix, inverse does not exist.",
59
+ matrixNotSquare: () => "Matrix: Must be square for inversion.",
60
+ matrixNotRectangular: () => "Matrix: Must be rectangular for transposition.",
61
+ matrixRowMismatch: (expected, got) => `Matrix: Expected row length ${expected}, but got ${got}.`
62
+ };
63
+
64
+ // src/common/index.ts
65
+ var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
66
+ DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
67
+ DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
68
+ return DFSOperation2;
69
+ })(DFSOperation || {});
70
+ var Range = class {
71
+ constructor(low, high, includeLow = true, includeHigh = true) {
72
+ this.low = low;
73
+ this.high = high;
74
+ this.includeLow = includeLow;
75
+ this.includeHigh = includeHigh;
76
+ }
77
+ // Determine whether a key is within the range
78
+ isInRange(key, comparator) {
79
+ const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
80
+ const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
81
+ return lowCheck && highCheck;
82
+ }
83
+ };
84
+
38
85
  // src/data-structures/base/iterable-element-base.ts
39
86
  var IterableElementBase = class {
40
87
  /**
@@ -57,7 +104,7 @@ var priorityQueueTyped = (() => {
57
104
  if (options) {
58
105
  const { toElementFn } = options;
59
106
  if (typeof toElementFn === "function") this._toElementFn = toElementFn;
60
- else if (toElementFn) throw new TypeError("toElementFn must be a function type");
107
+ else if (toElementFn) throw new TypeError(ERR.notAFunction("toElementFn"));
61
108
  }
62
109
  }
63
110
  /**
@@ -213,7 +260,7 @@ var priorityQueueTyped = (() => {
213
260
  acc = initialValue;
214
261
  } else {
215
262
  const first = iter.next();
216
- if (first.done) throw new TypeError("Reduce of empty structure with no initial value");
263
+ if (first.done) throw new TypeError(ERR.reduceEmpty());
217
264
  acc = first.value;
218
265
  index = 1;
219
266
  }
@@ -270,7 +317,7 @@ var priorityQueueTyped = (() => {
270
317
  __publicField(this, "_elements", []);
271
318
  __publicField(this, "_DEFAULT_COMPARATOR", (a, b) => {
272
319
  if (typeof a === "object" || typeof b === "object") {
273
- throw TypeError("When comparing object types, define a custom comparator in options.");
320
+ throw new TypeError(ERR.comparatorRequired("Heap"));
274
321
  }
275
322
  if (a > b) return 1;
276
323
  if (a < b) return -1;
@@ -580,7 +627,7 @@ var priorityQueueTyped = (() => {
580
627
  */
581
628
  map(callback, options, thisArg) {
582
629
  const { comparator, toElementFn, ...rest } = options != null ? options : {};
583
- if (!comparator) throw new TypeError("Heap.map requires options.comparator for EM");
630
+ if (!comparator) throw new TypeError(ERR.comparatorRequired("Heap.map"));
584
631
  const out = this._createLike([], { ...rest, comparator, toElementFn });
585
632
  let i = 0;
586
633
  for (const x of this) {
@@ -708,7 +755,7 @@ var priorityQueueTyped = (() => {
708
755
  __publicField(this, "_comparator");
709
756
  this.clear();
710
757
  this._comparator = comparator || this._defaultComparator;
711
- if (typeof this.comparator !== "function") throw new Error("FibonacciHeap: comparator must be a function.");
758
+ if (typeof this.comparator !== "function") throw new TypeError(ERR.notAFunction("comparator", "FibonacciHeap"));
712
759
  }
713
760
  /**
714
761
  * Get the circular root list head.
@@ -917,9 +964,7 @@ var priorityQueueTyped = (() => {
917
964
  super(elements, {
918
965
  comparator: (a, b) => {
919
966
  if (typeof a === "object" || typeof b === "object") {
920
- throw TypeError(
921
- `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`
922
- );
967
+ throw new TypeError(ERR.comparatorRequired("MaxHeap"));
923
968
  }
924
969
  if (a < b) return 1;
925
970
  if (a > b) return -1;
@@ -975,9 +1020,7 @@ var priorityQueueTyped = (() => {
975
1020
  super(elements, {
976
1021
  comparator: (a, b) => {
977
1022
  if (typeof a === "object" || typeof b === "object") {
978
- throw TypeError(
979
- `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`
980
- );
1023
+ throw new TypeError(ERR.comparatorRequired("MaxPriorityQueue"));
981
1024
  }
982
1025
  if (a < b) return 1;
983
1026
  if (a > b) return -1;
@@ -987,27 +1030,6 @@ var priorityQueueTyped = (() => {
987
1030
  });
988
1031
  }
989
1032
  };
990
-
991
- // src/common/index.ts
992
- var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
993
- DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
994
- DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
995
- return DFSOperation2;
996
- })(DFSOperation || {});
997
- var Range = class {
998
- constructor(low, high, includeLow = true, includeHigh = true) {
999
- this.low = low;
1000
- this.high = high;
1001
- this.includeLow = includeLow;
1002
- this.includeHigh = includeHigh;
1003
- }
1004
- // Determine whether a key is within the range
1005
- isInRange(key, comparator) {
1006
- const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
1007
- const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
1008
- return lowCheck && highCheck;
1009
- }
1010
- };
1011
1033
  return __toCommonJS(src_exports);
1012
1034
  })();
1013
1035
  /**