directed-graph-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 +144 -29
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +145 -28
  4. package/dist/cjs-legacy/index.cjs.map +1 -1
  5. package/dist/esm/index.mjs +144 -30
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +145 -29
  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/directed-graph-typed.js +143 -26
  19. package/dist/umd/directed-graph-typed.js.map +1 -1
  20. package/dist/umd/directed-graph-typed.min.js +3 -1
  21. package/dist/umd/directed-graph-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
@@ -24,6 +24,55 @@ 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 {
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
+ static {
66
+ __name(this, "Range");
67
+ }
68
+ // Determine whether a key is within the range
69
+ isInRange(key, comparator) {
70
+ const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
71
+ const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
72
+ return lowCheck && highCheck;
73
+ }
74
+ };
75
+
27
76
  // src/data-structures/base/iterable-entry-base.ts
28
77
  var IterableEntryBase = class {
29
78
  static {
@@ -224,7 +273,7 @@ var IterableElementBase = class {
224
273
  if (options) {
225
274
  const { toElementFn } = options;
226
275
  if (typeof toElementFn === "function") this._toElementFn = toElementFn;
227
- else if (toElementFn) throw new TypeError("toElementFn must be a function type");
276
+ else if (toElementFn) throw new TypeError(ERR.notAFunction("toElementFn"));
228
277
  }
229
278
  }
230
279
  /**
@@ -387,7 +436,7 @@ var IterableElementBase = class {
387
436
  acc = initialValue;
388
437
  } else {
389
438
  const first = iter.next();
390
- if (first.done) throw new TypeError("Reduce of empty structure with no initial value");
439
+ if (first.done) throw new TypeError(ERR.reduceEmpty());
391
440
  acc = first.value;
392
441
  index = 1;
393
442
  }
@@ -747,7 +796,7 @@ var Heap = class _Heap extends IterableElementBase {
747
796
  */
748
797
  map(callback, options, thisArg) {
749
798
  const { comparator, toElementFn, ...rest } = options ?? {};
750
- if (!comparator) throw new TypeError("Heap.map requires options.comparator for EM");
799
+ if (!comparator) throw new TypeError(ERR.comparatorRequired("Heap.map"));
751
800
  const out = this._createLike([], { ...rest, comparator, toElementFn });
752
801
  let i = 0;
753
802
  for (const x of this) {
@@ -774,7 +823,7 @@ var Heap = class _Heap extends IterableElementBase {
774
823
  }
775
824
  _DEFAULT_COMPARATOR = /* @__PURE__ */ __name((a, b) => {
776
825
  if (typeof a === "object" || typeof b === "object") {
777
- throw TypeError("When comparing object types, define a custom comparator in options.");
826
+ throw new TypeError(ERR.comparatorRequired("Heap"));
778
827
  }
779
828
  if (a > b) return 1;
780
829
  if (a < b) return -1;
@@ -1561,7 +1610,7 @@ var AbstractGraph = class extends IterableEntryBase {
1561
1610
  const newEdge = this.createEdge(srcOrEdge, dest, weight, value);
1562
1611
  return this._addEdge(newEdge);
1563
1612
  } else {
1564
- throw new Error("dest must be a Vertex or vertex key while srcOrEdge is an Edge");
1613
+ throw new TypeError(ERR.invalidArgument("dest must be a Vertex or vertex key when srcOrEdge is an Edge.", "Graph"));
1565
1614
  }
1566
1615
  }
1567
1616
  }
@@ -2241,6 +2290,92 @@ var AbstractGraph = class extends IterableEntryBase {
2241
2290
  _getVertexKey(vertexOrKey) {
2242
2291
  return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;
2243
2292
  }
2293
+ /**
2294
+ * The edge connector string used in visual output.
2295
+ * Override in subclasses (e.g., '--' for undirected, '->' for directed).
2296
+ */
2297
+ get _edgeConnector() {
2298
+ return "--";
2299
+ }
2300
+ /**
2301
+ * Generate a text-based visual representation of the graph.
2302
+ *
2303
+ * **Adjacency list format:**
2304
+ * ```
2305
+ * Graph (5 vertices, 6 edges):
2306
+ * A -> B (1), C (2)
2307
+ * B -> D (3)
2308
+ * C -> (no outgoing edges)
2309
+ * D -> A (1)
2310
+ * E (isolated)
2311
+ * ```
2312
+ *
2313
+ * @param options - Optional display settings.
2314
+ * @param options.showWeight - Whether to show edge weights (default: true).
2315
+ * @returns The visual string.
2316
+ */
2317
+ toVisual(options) {
2318
+ const showWeight = options?.showWeight ?? true;
2319
+ const vertices = [...this._vertexMap.values()];
2320
+ const vertexCount = vertices.length;
2321
+ const edgeCount = this.edgeSet().length;
2322
+ const lines = [`Graph (${vertexCount} vertices, ${edgeCount} edges):`];
2323
+ for (const vertex of vertices) {
2324
+ const neighbors = this.getNeighbors(vertex);
2325
+ if (neighbors.length === 0) {
2326
+ lines.push(` ${vertex.key} (isolated)`);
2327
+ } else {
2328
+ const edgeStrs = neighbors.map((neighbor) => {
2329
+ const edge = this.getEdge(vertex, neighbor);
2330
+ if (edge && showWeight && edge.weight !== void 0 && edge.weight !== 1) {
2331
+ return `${neighbor.key} (${edge.weight})`;
2332
+ }
2333
+ return `${neighbor.key}`;
2334
+ });
2335
+ lines.push(` ${vertex.key} ${this._edgeConnector} ${edgeStrs.join(", ")}`);
2336
+ }
2337
+ }
2338
+ return lines.join("\n");
2339
+ }
2340
+ /**
2341
+ * Generate DOT language representation for Graphviz.
2342
+ *
2343
+ * @param options - Optional display settings.
2344
+ * @param options.name - Graph name (default: 'G').
2345
+ * @param options.showWeight - Whether to label edges with weight (default: true).
2346
+ * @returns DOT format string.
2347
+ */
2348
+ toDot(options) {
2349
+ const name = options?.name ?? "G";
2350
+ const showWeight = options?.showWeight ?? 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
+ }
2244
2379
  };
2245
2380
 
2246
2381
  // src/data-structures/graph/directed-graph.ts
@@ -2276,6 +2411,9 @@ var DirectedGraph = class _DirectedGraph extends AbstractGraph {
2276
2411
  constructor(options) {
2277
2412
  super(options);
2278
2413
  }
2414
+ get _edgeConnector() {
2415
+ return "->";
2416
+ }
2279
2417
  _outEdgeMap = /* @__PURE__ */ new Map();
2280
2418
  get outEdgeMap() {
2281
2419
  return this._outEdgeMap;
@@ -2722,30 +2860,6 @@ var DirectedGraph = class _DirectedGraph extends AbstractGraph {
2722
2860
  }
2723
2861
  }
2724
2862
  };
2725
-
2726
- // src/common/index.ts
2727
- var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
2728
- DFSOperation2[DFSOperation2["VISIT"] = 0] = "VISIT";
2729
- DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
2730
- return DFSOperation2;
2731
- })(DFSOperation || {});
2732
- var Range = class {
2733
- constructor(low, high, includeLow = true, includeHigh = true) {
2734
- this.low = low;
2735
- this.high = high;
2736
- this.includeLow = includeLow;
2737
- this.includeHigh = includeHigh;
2738
- }
2739
- static {
2740
- __name(this, "Range");
2741
- }
2742
- // Determine whether a key is within the range
2743
- isInRange(key, comparator) {
2744
- const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
2745
- const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
2746
- return lowCheck && highCheck;
2747
- }
2748
- };
2749
2863
  /**
2750
2864
  * data-structure-typed
2751
2865
  *
@@ -2761,6 +2875,7 @@ exports.DFSOperation = DFSOperation;
2761
2875
  exports.DirectedEdge = DirectedEdge;
2762
2876
  exports.DirectedGraph = DirectedGraph;
2763
2877
  exports.DirectedVertex = DirectedVertex;
2878
+ exports.ERR = ERR;
2764
2879
  exports.Range = Range;
2765
2880
  //# sourceMappingURL=index.cjs.map
2766
2881
  //# sourceMappingURL=index.cjs.map