Skip to content

Commit

Permalink
feat: Introduce optional limit for countPathsToRoot
Browse files Browse the repository at this point in the history
  • Loading branch information
darscan committed Oct 16, 2023
1 parent ce229ac commit ee11833
Show file tree
Hide file tree
Showing 5 changed files with 793 additions and 27 deletions.
28 changes: 21 additions & 7 deletions src/core/dep-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,16 +149,23 @@ class DepGraphImpl implements types.DepGraphInternal {
return pathsToRoot.sort((a, b) => a.length - b.length);
}

public countPathsToRoot(pkg: types.Pkg): number {
public countPathsToRoot(pkg: types.Pkg, opts?: { limit?: number }): number {
let count = 0;
const limit = opts?.limit;
for (const nodeId of this.getPkgNodeIds(pkg)) {
if (this._countNodePathsToRootCache.has(nodeId)) {
count += this._countNodePathsToRootCache.get(nodeId)!;
} else {
const c = this.countNodePathsToRoot(nodeId);
this._countNodePathsToRootCache.set(nodeId, c);
const c = this.countNodePathsToRoot(nodeId, limit);
// don't cache if a limit was supplied
if (!limit) {
this._countNodePathsToRootCache.set(nodeId, c);
}
count += c;
}
if (limit && count >= limit) {
return limit;
}
}
return count;
}
Expand Down Expand Up @@ -372,15 +379,22 @@ class DepGraphImpl implements types.DepGraphInternal {
return allPaths;
}

private countNodePathsToRoot(nodeId: string, visited: string[] = []): number {
private countNodePathsToRoot(
nodeId: string,
limit = 0,
count = 0,
visited: string[] = [],
): number {
if (nodeId === this._rootNodeId) {
return 1;
return count + 1;
}
visited = visited.concat(nodeId);
let count = 0;
for (const parentNodeId of this.getNodeParentsNodeIds(nodeId)) {
if (!visited.includes(parentNodeId)) {
count += this.countNodePathsToRoot(parentNodeId, visited);
count = this.countNodePathsToRoot(parentNodeId, limit, count, visited);
if (limit && count >= limit) {
return limit;
}
}
}
return count;
Expand Down
2 changes: 1 addition & 1 deletion src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export interface DepGraph {
pkgPathsToRoot(pkg: Pkg, opts?: { limit?: number }): PkgInfo[][];
isTransitive(pkg: Pkg): boolean;
directDepsLeadingTo(pkg: Pkg): PkgInfo[];
countPathsToRoot(pkg: Pkg): number;
countPathsToRoot(pkg: Pkg, opts?: { limit?: number }): number;
equals(other: DepGraph, options?: { compareRoot?: boolean }): boolean;
}

Expand Down
Loading

0 comments on commit ee11833

Please sign in to comment.