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
@@ -24,6 +24,54 @@ var arrayRemove = /* @__PURE__ */ __name(function(array, predicate) {
24
24
  return result;
25
25
  }, "arrayRemove");
26
26
 
27
+ // src/common/error.ts
28
+ var ERR = {
29
+ // Range / index
30
+ indexOutOfRange: /* @__PURE__ */ __name((index, min, max, ctx) => `${ctx ? ctx + ": " : ""}Index ${index} is out of range [${min}, ${max}].`, "indexOutOfRange"),
31
+ invalidIndex: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Index must be an integer.`, "invalidIndex"),
32
+ // Type / argument
33
+ invalidArgument: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidArgument"),
34
+ comparatorRequired: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Comparator is required for non-number/non-string/non-Date keys.`, "comparatorRequired"),
35
+ invalidKey: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidKey"),
36
+ notAFunction: /* @__PURE__ */ __name((name, ctx) => `${ctx ? ctx + ": " : ""}${name} must be a function.`, "notAFunction"),
37
+ invalidEntry: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Each entry must be a [key, value] tuple.`, "invalidEntry"),
38
+ invalidNaN: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}NaN is not a valid key.`, "invalidNaN"),
39
+ invalidDate: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Invalid Date key.`, "invalidDate"),
40
+ reduceEmpty: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Reduce of empty structure with no initial value.`, "reduceEmpty"),
41
+ callbackReturnType: /* @__PURE__ */ __name((expected, got, ctx) => `${ctx ? ctx + ": " : ""}Callback must return ${expected}; got ${got}.`, "callbackReturnType"),
42
+ // State / operation
43
+ invalidOperation: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidOperation"),
44
+ // Matrix
45
+ matrixDimensionMismatch: /* @__PURE__ */ __name((op) => `Matrix: Dimensions must be compatible for ${op}.`, "matrixDimensionMismatch"),
46
+ matrixSingular: /* @__PURE__ */ __name(() => "Matrix: Singular matrix, inverse does not exist.", "matrixSingular"),
47
+ matrixNotSquare: /* @__PURE__ */ __name(() => "Matrix: Must be square for inversion.", "matrixNotSquare"),
48
+ matrixNotRectangular: /* @__PURE__ */ __name(() => "Matrix: Must be rectangular for transposition.", "matrixNotRectangular"),
49
+ matrixRowMismatch: /* @__PURE__ */ __name((expected, got) => `Matrix: Expected row length ${expected}, but got ${got}.`, "matrixRowMismatch")
50
+ };
51
+
52
+ // src/common/index.ts
53
+ var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
54
+ DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
55
+ DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
56
+ return DFSOperation2;
57
+ })(DFSOperation || {});
58
+ var _Range = class _Range {
59
+ constructor(low, high, includeLow = true, includeHigh = true) {
60
+ this.low = low;
61
+ this.high = high;
62
+ this.includeLow = includeLow;
63
+ this.includeHigh = includeHigh;
64
+ }
65
+ // Determine whether a key is within the range
66
+ isInRange(key, comparator) {
67
+ const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
68
+ const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
69
+ return lowCheck && highCheck;
70
+ }
71
+ };
72
+ __name(_Range, "Range");
73
+ var Range = _Range;
74
+
27
75
  // src/data-structures/base/iterable-entry-base.ts
28
76
  var _IterableEntryBase = class _IterableEntryBase {
29
77
  /**
@@ -227,7 +275,7 @@ var _IterableElementBase = class _IterableElementBase {
227
275
  if (options) {
228
276
  const { toElementFn } = options;
229
277
  if (typeof toElementFn === "function") this._toElementFn = toElementFn;
230
- else if (toElementFn) throw new TypeError("toElementFn must be a function type");
278
+ else if (toElementFn) throw new TypeError(ERR.notAFunction("toElementFn"));
231
279
  }
232
280
  }
233
281
  /**
@@ -383,7 +431,7 @@ var _IterableElementBase = class _IterableElementBase {
383
431
  acc = initialValue;
384
432
  } else {
385
433
  const first = iter.next();
386
- if (first.done) throw new TypeError("Reduce of empty structure with no initial value");
434
+ if (first.done) throw new TypeError(ERR.reduceEmpty());
387
435
  acc = first.value;
388
436
  index = 1;
389
437
  }
@@ -442,7 +490,7 @@ var _Heap = class _Heap extends IterableElementBase {
442
490
  __publicField(this, "_elements", []);
443
491
  __publicField(this, "_DEFAULT_COMPARATOR", /* @__PURE__ */ __name((a, b) => {
444
492
  if (typeof a === "object" || typeof b === "object") {
445
- throw TypeError("When comparing object types, define a custom comparator in options.");
493
+ throw new TypeError(ERR.comparatorRequired("Heap"));
446
494
  }
447
495
  if (a > b) return 1;
448
496
  if (a < b) return -1;
@@ -752,7 +800,7 @@ var _Heap = class _Heap extends IterableElementBase {
752
800
  */
753
801
  map(callback, options, thisArg) {
754
802
  const { comparator, toElementFn, ...rest } = options != null ? options : {};
755
- if (!comparator) throw new TypeError("Heap.map requires options.comparator for EM");
803
+ if (!comparator) throw new TypeError(ERR.comparatorRequired("Heap.map"));
756
804
  const out = this._createLike([], { ...rest, comparator, toElementFn });
757
805
  let i = 0;
758
806
  for (const x of this) {
@@ -777,11 +825,6 @@ var _Heap = class _Heap extends IterableElementBase {
777
825
  }
778
826
  return out;
779
827
  }
780
- /**
781
- * Get the comparator used to order elements.
782
- * @remarks Time O(1), Space O(1)
783
- * @returns Comparator function.
784
- */
785
828
  /**
786
829
  * Get the comparator used to order elements.
787
830
  * @remarks Time O(1), Space O(1)
@@ -830,8 +873,7 @@ var _Heap = class _Heap extends IterableElementBase {
830
873
  */
831
874
  _createInstance(options) {
832
875
  const Ctor = this.constructor;
833
- const next = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...options != null ? options : {} });
834
- return next;
876
+ return new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...options != null ? options : {} });
835
877
  }
836
878
  /**
837
879
  * (Protected) Create a like-kind instance seeded by elements.
@@ -1560,7 +1602,7 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
1560
1602
  const newEdge = this.createEdge(srcOrEdge, dest, weight, value);
1561
1603
  return this._addEdge(newEdge);
1562
1604
  } else {
1563
- throw new Error("dest must be a Vertex or vertex key while srcOrEdge is an Edge");
1605
+ throw new TypeError(ERR.invalidArgument("dest must be a Vertex or vertex key when srcOrEdge is an Edge.", "Graph"));
1564
1606
  }
1565
1607
  }
1566
1608
  }
@@ -2169,8 +2211,8 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
2169
2211
  const Ctor = this.constructor;
2170
2212
  const instance = new Ctor();
2171
2213
  const graph = _options == null ? void 0 : _options.graph;
2172
- if (graph) instance._options = { ...instance._options, ...graph };
2173
- else instance._options = { ...instance._options, ...this._options };
2214
+ if (graph) instance["_options"] = { ...instance["_options"], ...graph };
2215
+ else instance["_options"] = { ...instance["_options"], ...this._options };
2174
2216
  return instance;
2175
2217
  }
2176
2218
  /**
@@ -2203,12 +2245,10 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
2203
2245
  const [va, vb] = ends;
2204
2246
  const ka = va.key;
2205
2247
  const kb = vb.key;
2206
- const hasA = g.hasVertex ? g.hasVertex(ka) : false;
2207
- const hasB = g.hasVertex ? g.hasVertex(kb) : false;
2248
+ const hasA = typeof g.hasVertex === "function" ? g.hasVertex(ka) : false;
2249
+ const hasB = typeof g.hasVertex === "function" ? g.hasVertex(kb) : false;
2208
2250
  if (hasA && hasB) {
2209
- const w = e.weight;
2210
- const val = e.value;
2211
- const newEdge = g.createEdge(ka, kb, w, val);
2251
+ const newEdge = g.createEdge(ka, kb, e.weight, e.value);
2212
2252
  g._addEdge(newEdge);
2213
2253
  }
2214
2254
  }
@@ -2246,6 +2286,94 @@ var _AbstractGraph = class _AbstractGraph extends IterableEntryBase {
2246
2286
  _getVertexKey(vertexOrKey) {
2247
2287
  return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
2248
2288
  }
2289
+ /**
2290
+ * The edge connector string used in visual output.
2291
+ * Override in subclasses (e.g., '--' for undirected, '->' for directed).
2292
+ */
2293
+ get _edgeConnector() {
2294
+ return "--";
2295
+ }
2296
+ /**
2297
+ * Generate a text-based visual representation of the graph.
2298
+ *
2299
+ * **Adjacency list format:**
2300
+ * ```
2301
+ * Graph (5 vertices, 6 edges):
2302
+ * A -> B (1), C (2)
2303
+ * B -> D (3)
2304
+ * C -> (no outgoing edges)
2305
+ * D -> A (1)
2306
+ * E (isolated)
2307
+ * ```
2308
+ *
2309
+ * @param options - Optional display settings.
2310
+ * @param options.showWeight - Whether to show edge weights (default: true).
2311
+ * @returns The visual string.
2312
+ */
2313
+ toVisual(options) {
2314
+ var _a;
2315
+ const showWeight = (_a = options == null ? void 0 : options.showWeight) != null ? _a : true;
2316
+ const vertices = [...this._vertexMap.values()];
2317
+ const vertexCount = vertices.length;
2318
+ const edgeCount = this.edgeSet().length;
2319
+ const lines = [`Graph (${vertexCount} vertices, ${edgeCount} edges):`];
2320
+ for (const vertex of vertices) {
2321
+ const neighbors = this.getNeighbors(vertex);
2322
+ if (neighbors.length === 0) {
2323
+ lines.push(` ${vertex.key} (isolated)`);
2324
+ } else {
2325
+ const edgeStrs = neighbors.map((neighbor) => {
2326
+ const edge = this.getEdge(vertex, neighbor);
2327
+ if (edge && showWeight && edge.weight !== void 0 && edge.weight !== 1) {
2328
+ return `${neighbor.key} (${edge.weight})`;
2329
+ }
2330
+ return `${neighbor.key}`;
2331
+ });
2332
+ lines.push(` ${vertex.key} ${this._edgeConnector} ${edgeStrs.join(", ")}`);
2333
+ }
2334
+ }
2335
+ return lines.join("\n");
2336
+ }
2337
+ /**
2338
+ * Generate DOT language representation for Graphviz.
2339
+ *
2340
+ * @param options - Optional display settings.
2341
+ * @param options.name - Graph name (default: 'G').
2342
+ * @param options.showWeight - Whether to label edges with weight (default: true).
2343
+ * @returns DOT format string.
2344
+ */
2345
+ toDot(options) {
2346
+ var _a, _b;
2347
+ const name = (_a = options == null ? void 0 : options.name) != null ? _a : "G";
2348
+ const showWeight = (_b = options == null ? void 0 : options.showWeight) != null ? _b : true;
2349
+ const isDirected = this._edgeConnector === "->";
2350
+ const graphType = isDirected ? "digraph" : "graph";
2351
+ const edgeOp = isDirected ? "->" : "--";
2352
+ const lines = [`${graphType} ${name} {`];
2353
+ for (const vertex of this._vertexMap.values()) {
2354
+ lines.push(` "${vertex.key}";`);
2355
+ }
2356
+ const visited = /* @__PURE__ */ new Set();
2357
+ for (const vertex of this._vertexMap.values()) {
2358
+ for (const neighbor of this.getNeighbors(vertex)) {
2359
+ const edgeId = isDirected ? `${vertex.key}->${neighbor.key}` : [vertex.key, neighbor.key].sort().join("--");
2360
+ if (visited.has(edgeId)) continue;
2361
+ visited.add(edgeId);
2362
+ const edge = this.getEdge(vertex, neighbor);
2363
+ const label = edge && showWeight && edge.weight !== void 0 && edge.weight !== 1 ? ` [label="${edge.weight}"]` : "";
2364
+ lines.push(` "${vertex.key}" ${edgeOp} "${neighbor.key}"${label};`);
2365
+ }
2366
+ }
2367
+ lines.push("}");
2368
+ return lines.join("\n");
2369
+ }
2370
+ /**
2371
+ * Print the graph to console.
2372
+ * @param options - Display settings passed to `toVisual`.
2373
+ */
2374
+ print(options) {
2375
+ console.log(this.toVisual(options));
2376
+ }
2249
2377
  };
2250
2378
  __name(_AbstractGraph, "AbstractGraph");
2251
2379
  var AbstractGraph = _AbstractGraph;
@@ -2280,6 +2408,9 @@ var _DirectedGraph = class _DirectedGraph extends AbstractGraph {
2280
2408
  __publicField(this, "_outEdgeMap", /* @__PURE__ */ new Map());
2281
2409
  __publicField(this, "_inEdgeMap", /* @__PURE__ */ new Map());
2282
2410
  }
2411
+ get _edgeConnector() {
2412
+ return "->";
2413
+ }
2283
2414
  get outEdgeMap() {
2284
2415
  return this._outEdgeMap;
2285
2416
  }
@@ -2727,29 +2858,6 @@ var _DirectedGraph = class _DirectedGraph extends AbstractGraph {
2727
2858
  };
2728
2859
  __name(_DirectedGraph, "DirectedGraph");
2729
2860
  var DirectedGraph = _DirectedGraph;
2730
-
2731
- // src/common/index.ts
2732
- var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
2733
- DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
2734
- DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
2735
- return DFSOperation2;
2736
- })(DFSOperation || {});
2737
- var _Range = class _Range {
2738
- constructor(low, high, includeLow = true, includeHigh = true) {
2739
- this.low = low;
2740
- this.high = high;
2741
- this.includeLow = includeLow;
2742
- this.includeHigh = includeHigh;
2743
- }
2744
- // Determine whether a key is within the range
2745
- isInRange(key, comparator) {
2746
- const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
2747
- const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
2748
- return lowCheck && highCheck;
2749
- }
2750
- };
2751
- __name(_Range, "Range");
2752
- var Range = _Range;
2753
2861
  /**
2754
2862
  * data-structure-typed
2755
2863
  *
@@ -2758,6 +2866,6 @@ var Range = _Range;
2758
2866
  * @license MIT License
2759
2867
  */
2760
2868
 
2761
- export { AbstractEdge, AbstractGraph, AbstractVertex, DFSOperation, DirectedEdge, DirectedGraph, DirectedVertex, Range };
2869
+ export { AbstractEdge, AbstractGraph, AbstractVertex, DFSOperation, DirectedEdge, DirectedGraph, DirectedVertex, ERR, Range };
2762
2870
  //# sourceMappingURL=index.mjs.map
2763
2871
  //# sourceMappingURL=index.mjs.map