Skip to content

Commit

Permalink
fix: stop on cycles
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Feb 10, 2025
1 parent 3179609 commit 059e817
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/core/injector/topology-tree/topology-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ export class TopologyTree {
}
if (this.links.has(child)) {
const existingSubtree = this.links.get(child)!;
const existingDepth = existingSubtree.getDepth({ stopOn: node.value });

if (node.hasCycleWith(child)) {
return;
}
const existingDepth = existingSubtree.getDepth();
if (existingDepth < depth) {
existingSubtree.relink(node);
}
Expand Down
40 changes: 40 additions & 0 deletions packages/core/injector/topology-tree/tree-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,47 @@ export class TreeNode<T> {
}

relink(parent: TreeNode<T>) {
this.parent?.removeChild(this);

this.parent = parent;
this.parent.addChild(this);
}

getDepth() {
const visited = new Set<TreeNode<T>>();

let depth = 0;
let current: TreeNode<T> | null = this;

while (current) {
depth++;
current = current.parent;

// Stop on cycle
if (visited.has(current!)) {
return -1;
}
visited.add(current!);
}
return depth;
}

hasCycleWith(target: T) {
const visited = new Set<TreeNode<T>>();

let current: TreeNode<T> | null = this;

while (current) {
if (current.value === target) {
return true;
}
current = current.parent;

if (visited.has(current!)) {
return false;
}
visited.add(current!);
}
return false;
}
}

0 comments on commit 059e817

Please sign in to comment.