Skip to content

Commit ee11833

Browse files
committed
feat: Introduce optional limit for countPathsToRoot
1 parent ce229ac commit ee11833

File tree

5 files changed

+793
-27
lines changed

5 files changed

+793
-27
lines changed

src/core/dep-graph.ts

+21-7
Original file line numberDiff line numberDiff line change
@@ -149,16 +149,23 @@ class DepGraphImpl implements types.DepGraphInternal {
149149
return pathsToRoot.sort((a, b) => a.length - b.length);
150150
}
151151

152-
public countPathsToRoot(pkg: types.Pkg): number {
152+
public countPathsToRoot(pkg: types.Pkg, opts?: { limit?: number }): number {
153153
let count = 0;
154+
const limit = opts?.limit;
154155
for (const nodeId of this.getPkgNodeIds(pkg)) {
155156
if (this._countNodePathsToRootCache.has(nodeId)) {
156157
count += this._countNodePathsToRootCache.get(nodeId)!;
157158
} else {
158-
const c = this.countNodePathsToRoot(nodeId);
159-
this._countNodePathsToRootCache.set(nodeId, c);
159+
const c = this.countNodePathsToRoot(nodeId, limit);
160+
// don't cache if a limit was supplied
161+
if (!limit) {
162+
this._countNodePathsToRootCache.set(nodeId, c);
163+
}
160164
count += c;
161165
}
166+
if (limit && count >= limit) {
167+
return limit;
168+
}
162169
}
163170
return count;
164171
}
@@ -372,15 +379,22 @@ class DepGraphImpl implements types.DepGraphInternal {
372379
return allPaths;
373380
}
374381

375-
private countNodePathsToRoot(nodeId: string, visited: string[] = []): number {
382+
private countNodePathsToRoot(
383+
nodeId: string,
384+
limit = 0,
385+
count = 0,
386+
visited: string[] = [],
387+
): number {
376388
if (nodeId === this._rootNodeId) {
377-
return 1;
389+
return count + 1;
378390
}
379391
visited = visited.concat(nodeId);
380-
let count = 0;
381392
for (const parentNodeId of this.getNodeParentsNodeIds(nodeId)) {
382393
if (!visited.includes(parentNodeId)) {
383-
count += this.countNodePathsToRoot(parentNodeId, visited);
394+
count = this.countNodePathsToRoot(parentNodeId, limit, count, visited);
395+
if (limit && count >= limit) {
396+
return limit;
397+
}
384398
}
385399
}
386400
return count;

src/core/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ export interface DepGraph {
100100
pkgPathsToRoot(pkg: Pkg, opts?: { limit?: number }): PkgInfo[][];
101101
isTransitive(pkg: Pkg): boolean;
102102
directDepsLeadingTo(pkg: Pkg): PkgInfo[];
103-
countPathsToRoot(pkg: Pkg): number;
103+
countPathsToRoot(pkg: Pkg, opts?: { limit?: number }): number;
104104
equals(other: DepGraph, options?: { compareRoot?: boolean }): boolean;
105105
}
106106

0 commit comments

Comments
 (0)