directed-graph-typed 2.4.3 → 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 (65) hide show
  1. package/dist/cjs/index.cjs +150 -43
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +151 -42
  4. package/dist/cjs-legacy/index.cjs.map +1 -1
  5. package/dist/esm/index.mjs +150 -44
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +151 -43
  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/base/iterable-element-base.d.ts +1 -1
  12. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +15 -5
  13. package/dist/types/data-structures/binary-tree/bst.d.ts +1 -1
  14. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +7 -1
  15. package/dist/types/data-structures/graph/abstract-graph.d.ts +44 -0
  16. package/dist/types/data-structures/graph/directed-graph.d.ts +3 -2
  17. package/dist/types/data-structures/graph/undirected-graph.d.ts +16 -2
  18. package/dist/types/data-structures/hash/hash-map.d.ts +2 -2
  19. package/dist/types/data-structures/heap/heap.d.ts +3 -7
  20. package/dist/types/data-structures/queue/deque.d.ts +41 -1
  21. package/dist/types/types/data-structures/binary-tree/avl-tree.d.ts +1 -1
  22. package/dist/types/types/data-structures/binary-tree/red-black-tree.d.ts +1 -1
  23. package/dist/types/types/data-structures/linked-list/doubly-linked-list.d.ts +1 -1
  24. package/dist/types/types/data-structures/linked-list/singly-linked-list.d.ts +1 -1
  25. package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +1 -1
  26. package/dist/types/types/data-structures/queue/deque.d.ts +6 -0
  27. package/dist/types/types/data-structures/stack/stack.d.ts +1 -1
  28. package/dist/umd/directed-graph-typed.js +149 -40
  29. package/dist/umd/directed-graph-typed.js.map +1 -1
  30. package/dist/umd/directed-graph-typed.min.js +3 -1
  31. package/dist/umd/directed-graph-typed.min.js.map +1 -1
  32. package/package.json +2 -2
  33. package/src/common/error.ts +60 -0
  34. package/src/common/index.ts +2 -0
  35. package/src/data-structures/base/iterable-element-base.ts +5 -4
  36. package/src/data-structures/binary-tree/binary-indexed-tree.ts +6 -5
  37. package/src/data-structures/binary-tree/binary-tree.ts +121 -49
  38. package/src/data-structures/binary-tree/bst.ts +12 -4
  39. package/src/data-structures/binary-tree/red-black-tree.ts +20 -0
  40. package/src/data-structures/binary-tree/tree-map.ts +8 -7
  41. package/src/data-structures/binary-tree/tree-multi-map.ts +4 -4
  42. package/src/data-structures/binary-tree/tree-multi-set.ts +10 -9
  43. package/src/data-structures/binary-tree/tree-set.ts +7 -6
  44. package/src/data-structures/graph/abstract-graph.ts +124 -19
  45. package/src/data-structures/graph/directed-graph.ts +8 -4
  46. package/src/data-structures/graph/map-graph.ts +1 -1
  47. package/src/data-structures/graph/undirected-graph.ts +99 -4
  48. package/src/data-structures/hash/hash-map.ts +19 -6
  49. package/src/data-structures/heap/heap.ts +21 -17
  50. package/src/data-structures/heap/max-heap.ts +2 -3
  51. package/src/data-structures/linked-list/doubly-linked-list.ts +4 -4
  52. package/src/data-structures/linked-list/singly-linked-list.ts +15 -9
  53. package/src/data-structures/matrix/matrix.ts +9 -10
  54. package/src/data-structures/priority-queue/max-priority-queue.ts +2 -3
  55. package/src/data-structures/queue/deque.ts +72 -4
  56. package/src/data-structures/stack/stack.ts +1 -1
  57. package/src/data-structures/trie/trie.ts +12 -6
  58. package/src/types/data-structures/binary-tree/avl-tree.ts +1 -1
  59. package/src/types/data-structures/binary-tree/red-black-tree.ts +1 -1
  60. package/src/types/data-structures/linked-list/doubly-linked-list.ts +1 -1
  61. package/src/types/data-structures/linked-list/singly-linked-list.ts +1 -1
  62. package/src/types/data-structures/priority-queue/priority-queue.ts +1 -1
  63. package/src/types/data-structures/queue/deque.ts +7 -0
  64. package/src/types/data-structures/stack/stack.ts +1 -1
  65. package/src/utils/utils.ts +4 -2
@@ -26,6 +26,54 @@ var arrayRemove = /* @__PURE__ */ __name(function(array, predicate) {
26
26
  return result;
27
27
  }, "arrayRemove");
28
28
 
29
+ // src/common/error.ts
30
+ var ERR = {
31
+ // Range / index
32
+ indexOutOfRange: /* @__PURE__ */ __name((index, min, max, ctx) => `${ctx ? ctx + ": " : ""}Index ${index} is out of range [${min}, ${max}].`, "indexOutOfRange"),
33
+ invalidIndex: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Index must be an integer.`, "invalidIndex"),
34
+ // Type / argument
35
+ invalidArgument: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidArgument"),
36
+ comparatorRequired: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Comparator is required for non-number/non-string/non-Date keys.`, "comparatorRequired"),
37
+ invalidKey: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidKey"),
38
+ notAFunction: /* @__PURE__ */ __name((name, ctx) => `${ctx ? ctx + ": " : ""}${name} must be a function.`, "notAFunction"),
39
+ invalidEntry: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Each entry must be a [key, value] tuple.`, "invalidEntry"),
40
+ invalidNaN: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}NaN is not a valid key.`, "invalidNaN"),
41
+ invalidDate: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Invalid Date key.`, "invalidDate"),
42
+ reduceEmpty: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Reduce of empty structure with no initial value.`, "reduceEmpty"),
43
+ callbackReturnType: /* @__PURE__ */ __name((expected, got, ctx) => `${ctx ? ctx + ": " : ""}Callback must return ${expected}; got ${got}.`, "callbackReturnType"),
44
+ // State / operation
45
+ invalidOperation: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidOperation"),
46
+ // Matrix
47
+ matrixDimensionMismatch: /* @__PURE__ */ __name((op) => `Matrix: Dimensions must be compatible for ${op}.`, "matrixDimensionMismatch"),
48
+ matrixSingular: /* @__PURE__ */ __name(() => "Matrix: Singular matrix, inverse does not exist.", "matrixSingular"),
49
+ matrixNotSquare: /* @__PURE__ */ __name(() => "Matrix: Must be square for inversion.", "matrixNotSquare"),
50
+ matrixNotRectangular: /* @__PURE__ */ __name(() => "Matrix: Must be rectangular for transposition.", "matrixNotRectangular"),
51
+ matrixRowMismatch: /* @__PURE__ */ __name((expected, got) => `Matrix: Expected row length ${expected}, but got ${got}.`, "matrixRowMismatch")
52
+ };
53
+
54
+ // src/common/index.ts
55
+ var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
56
+ DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
57
+ DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
58
+ return DFSOperation2;
59
+ })(DFSOperation || {});
60
+ var _Range = class _Range {
61
+ constructor(low, high, includeLow = true, includeHigh = true) {
62
+ this.low = low;
63
+ this.high = high;
64
+ this.includeLow = includeLow;
65
+ this.includeHigh = includeHigh;
66
+ }
67
+ // Determine whether a key is within the range
68
+ isInRange(key, comparator) {
69
+ const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
70
+ const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
71
+ return lowCheck && highCheck;
72
+ }
73
+ };
74
+ __name(_Range, "Range");
75
+ var Range = _Range;
76
+
29
77
  // src/data-structures/base/iterable-entry-base.ts
30
78
  var _IterableEntryBase = class _IterableEntryBase {
31
79
  /**
@@ -229,7 +277,7 @@ var _IterableElementBase = class _IterableElementBase {
229
277
  if (options) {
230
278
  const { toElementFn } = options;
231
279
  if (typeof toElementFn === "function") this._toElementFn = toElementFn;
232
- else if (toElementFn) throw new TypeError("toElementFn must be a function type");
280
+ else if (toElementFn) throw new TypeError(ERR.notAFunction("toElementFn"));
233
281
  }
234
282
  }
235
283
  /**
@@ -385,7 +433,7 @@ var _IterableElementBase = class _IterableElementBase {
385
433
  acc = initialValue;
386
434
  } else {
387
435
  const first = iter.next();
388
- if (first.done) throw new TypeError("Reduce of empty structure with no initial value");
436
+ if (first.done) throw new TypeError(ERR.reduceEmpty());
389
437
  acc = first.value;
390
438
  index = 1;
391
439
  }
@@ -444,7 +492,7 @@ var _Heap = class _Heap extends IterableElementBase {
444
492
  __publicField(this, "_elements", []);
445
493
  __publicField(this, "_DEFAULT_COMPARATOR", /* @__PURE__ */ __name((a, b) => {
446
494
  if (typeof a === "object" || typeof b === "object") {
447
- throw TypeError("When comparing object types, define a custom comparator in options.");
495
+ throw new TypeError(ERR.comparatorRequired("Heap"));
448
496
  }
449
497
  if (a > b) return 1;
450
498
  if (a < b) return -1;
@@ -754,7 +802,7 @@ var _Heap = class _Heap extends IterableElementBase {
754
802
  */
755
803
  map(callback, options, thisArg) {
756
804
  const { comparator, toElementFn, ...rest } = options != null ? options : {};
757
- if (!comparator) throw new TypeError("Heap.map requires options.comparator for EM");
805
+ if (!comparator) throw new TypeError(ERR.comparatorRequired("Heap.map"));
758
806
  const out = this._createLike([], { ...rest, comparator, toElementFn });
759
807
  let i = 0;
760
808
  for (const x of this) {
@@ -779,11 +827,6 @@ var _Heap = class _Heap extends IterableElementBase {
779
827
  }
780
828
  return out;
781
829
  }
782
- /**
783
- * Get the comparator used to order elements.
784
- * @remarks Time O(1), Space O(1)
785
- * @returns Comparator function.
786
- */
787
830
  /**
788
831
  * Get the comparator used to order elements.
789
832
  * @remarks Time O(1), Space O(1)
@@ -832,8 +875,7 @@ var _Heap = class _Heap extends IterableElementBase {
832
875
  */
833
876
  _createInstance(options) {
834
877
  const Ctor = this.constructor;
835
- const next = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...options != null ? options : {} });
836
- return next;
878
+ return new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...options != null ? options : {} });
837
879
  }
838
880
  /**
839
881
  * (Protected) Create a like-kind instance seeded by elements.
@@ -1562,7 +1604,7 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
1562
1604
  const newEdge = this.createEdge(srcOrEdge, dest, weight, value);
1563
1605
  return this._addEdge(newEdge);
1564
1606
  } else {
1565
- throw new Error("dest must be a Vertex or vertex key while srcOrEdge is an Edge");
1607
+ throw new TypeError(ERR.invalidArgument("dest must be a Vertex or vertex key when srcOrEdge is an Edge.", "Graph"));
1566
1608
  }
1567
1609
  }
1568
1610
  }
@@ -2171,8 +2213,8 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
2171
2213
  const Ctor = this.constructor;
2172
2214
  const instance = new Ctor();
2173
2215
  const graph = _options == null ? void 0 : _options.graph;
2174
- if (graph) instance._options = { ...instance._options, ...graph };
2175
- else instance._options = { ...instance._options, ...this._options };
2216
+ if (graph) instance["_options"] = { ...instance["_options"], ...graph };
2217
+ else instance["_options"] = { ...instance["_options"], ...this._options };
2176
2218
  return instance;
2177
2219
  }
2178
2220
  /**
@@ -2205,12 +2247,10 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
2205
2247
  const [va, vb] = ends;
2206
2248
  const ka = va.key;
2207
2249
  const kb = vb.key;
2208
- const hasA = g.hasVertex ? g.hasVertex(ka) : false;
2209
- const hasB = g.hasVertex ? g.hasVertex(kb) : false;
2250
+ const hasA = typeof g.hasVertex === "function" ? g.hasVertex(ka) : false;
2251
+ const hasB = typeof g.hasVertex === "function" ? g.hasVertex(kb) : false;
2210
2252
  if (hasA && hasB) {
2211
- const w = e.weight;
2212
- const val = e.value;
2213
- const newEdge = g.createEdge(ka, kb, w, val);
2253
+ const newEdge = g.createEdge(ka, kb, e.weight, e.value);
2214
2254
  g._addEdge(newEdge);
2215
2255
  }
2216
2256
  }
@@ -2248,6 +2288,94 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
2248
2288
  _getVertexKey(vertexOrKey) {
2249
2289
  return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
2250
2290
  }
2291
+ /**
2292
+ * The edge connector string used in visual output.
2293
+ * Override in subclasses (e.g., '--' for undirected, '->' for directed).
2294
+ */
2295
+ get _edgeConnector() {
2296
+ return "--";
2297
+ }
2298
+ /**
2299
+ * Generate a text-based visual representation of the graph.
2300
+ *
2301
+ * **Adjacency list format:**
2302
+ * ```
2303
+ * Graph (5 vertices, 6 edges):
2304
+ * A -> B (1), C (2)
2305
+ * B -> D (3)
2306
+ * C -> (no outgoing edges)
2307
+ * D -> A (1)
2308
+ * E (isolated)
2309
+ * ```
2310
+ *
2311
+ * @param options - Optional display settings.
2312
+ * @param options.showWeight - Whether to show edge weights (default: true).
2313
+ * @returns The visual string.
2314
+ */
2315
+ toVisual(options) {
2316
+ var _a;
2317
+ const showWeight = (_a = options == null ? void 0 : options.showWeight) != null ? _a : true;
2318
+ const vertices = [...this._vertexMap.values()];
2319
+ const vertexCount = vertices.length;
2320
+ const edgeCount = this.edgeSet().length;
2321
+ const lines = [`Graph (${vertexCount} vertices, ${edgeCount} edges):`];
2322
+ for (const vertex of vertices) {
2323
+ const neighbors = this.getNeighbors(vertex);
2324
+ if (neighbors.length === 0) {
2325
+ lines.push(` ${vertex.key} (isolated)`);
2326
+ } else {
2327
+ const edgeStrs = neighbors.map((neighbor) => {
2328
+ const edge = this.getEdge(vertex, neighbor);
2329
+ if (edge && showWeight && edge.weight !== void 0 && edge.weight !== 1) {
2330
+ return `${neighbor.key} (${edge.weight})`;
2331
+ }
2332
+ return `${neighbor.key}`;
2333
+ });
2334
+ lines.push(` ${vertex.key} ${this._edgeConnector} ${edgeStrs.join(", ")}`);
2335
+ }
2336
+ }
2337
+ return lines.join("\n");
2338
+ }
2339
+ /**
2340
+ * Generate DOT language representation for Graphviz.
2341
+ *
2342
+ * @param options - Optional display settings.
2343
+ * @param options.name - Graph name (default: 'G').
2344
+ * @param options.showWeight - Whether to label edges with weight (default: true).
2345
+ * @returns DOT format string.
2346
+ */
2347
+ toDot(options) {
2348
+ var _a, _b;
2349
+ const name = (_a = options == null ? void 0 : options.name) != null ? _a : "G";
2350
+ const showWeight = (_b = options == null ? void 0 : options.showWeight) != null ? _b : true;
2351
+ const isDirected = this._edgeConnector === "->";
2352
+ const graphType = isDirected ? "digraph" : "graph";
2353
+ const edgeOp = isDirected ? "->" : "--";
2354
+ const lines = [`${graphType} ${name} {`];
2355
+ for (const vertex of this._vertexMap.values()) {
2356
+ lines.push(` "${vertex.key}";`);
2357
+ }
2358
+ const visited = /* @__PURE__ */ new Set();
2359
+ for (const vertex of this._vertexMap.values()) {
2360
+ for (const neighbor of this.getNeighbors(vertex)) {
2361
+ const edgeId = isDirected ? `${vertex.key}->${neighbor.key}` : [vertex.key, neighbor.key].sort().join("--");
2362
+ if (visited.has(edgeId)) continue;
2363
+ visited.add(edgeId);
2364
+ const edge = this.getEdge(vertex, neighbor);
2365
+ const label = edge && showWeight && edge.weight !== void 0 && edge.weight !== 1 ? ` [label="${edge.weight}"]` : "";
2366
+ lines.push(` "${vertex.key}" ${edgeOp} "${neighbor.key}"${label};`);
2367
+ }
2368
+ }
2369
+ lines.push("}");
2370
+ return lines.join("\n");
2371
+ }
2372
+ /**
2373
+ * Print the graph to console.
2374
+ * @param options - Display settings passed to `toVisual`.
2375
+ */
2376
+ print(options) {
2377
+ console.log(this.toVisual(options));
2378
+ }
2251
2379
  };
2252
2380
  __name(_AbstractGraph, "AbstractGraph");
2253
2381
  var AbstractGraph = _AbstractGraph;
@@ -2282,6 +2410,9 @@ var _DirectedGraph = class _DirectedGraph extends AbstractGraph {
2282
2410
  __publicField(this, "_outEdgeMap", /* @__PURE__ */ new Map());
2283
2411
  __publicField(this, "_inEdgeMap", /* @__PURE__ */ new Map());
2284
2412
  }
2413
+ get _edgeConnector() {
2414
+ return "->";
2415
+ }
2285
2416
  get outEdgeMap() {
2286
2417
  return this._outEdgeMap;
2287
2418
  }
@@ -2729,29 +2860,6 @@ var _DirectedGraph = class _DirectedGraph extends AbstractGraph {
2729
2860
  };
2730
2861
  __name(_DirectedGraph, "DirectedGraph");
2731
2862
  var DirectedGraph = _DirectedGraph;
2732
-
2733
- // src/common/index.ts
2734
- var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
2735
- DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
2736
- DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
2737
- return DFSOperation2;
2738
- })(DFSOperation || {});
2739
- var _Range = class _Range {
2740
- constructor(low, high, includeLow = true, includeHigh = true) {
2741
- this.low = low;
2742
- this.high = high;
2743
- this.includeLow = includeLow;
2744
- this.includeHigh = includeHigh;
2745
- }
2746
- // Determine whether a key is within the range
2747
- isInRange(key, comparator) {
2748
- const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
2749
- const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
2750
- return lowCheck && highCheck;
2751
- }
2752
- };
2753
- __name(_Range, "Range");
2754
- var Range = _Range;
2755
2863
  /**
2756
2864
  * data-structure-typed
2757
2865
  *
@@ -2767,6 +2875,7 @@ exports.DFSOperation = DFSOperation;
2767
2875
  exports.DirectedEdge = DirectedEdge;
2768
2876
  exports.DirectedGraph = DirectedGraph;
2769
2877
  exports.DirectedVertex = DirectedVertex;
2878
+ exports.ERR = ERR;
2770
2879
  exports.Range = Range;
2771
2880
  //# sourceMappingURL=index.cjs.map
2772
2881
  //# sourceMappingURL=index.cjs.map