@@ -149,16 +149,23 @@ class DepGraphImpl implements types.DepGraphInternal {
149
149
return pathsToRoot . sort ( ( a , b ) => a . length - b . length ) ;
150
150
}
151
151
152
- public countPathsToRoot ( pkg : types . Pkg ) : number {
152
+ public countPathsToRoot ( pkg : types . Pkg , opts ?: { limit ?: number } ) : number {
153
153
let count = 0 ;
154
+ const limit = opts ?. limit ;
154
155
for ( const nodeId of this . getPkgNodeIds ( pkg ) ) {
155
156
if ( this . _countNodePathsToRootCache . has ( nodeId ) ) {
156
157
count += this . _countNodePathsToRootCache . get ( nodeId ) ! ;
157
158
} 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
+ }
160
164
count += c ;
161
165
}
166
+ if ( limit && count >= limit ) {
167
+ return limit ;
168
+ }
162
169
}
163
170
return count ;
164
171
}
@@ -372,15 +379,22 @@ class DepGraphImpl implements types.DepGraphInternal {
372
379
return allPaths ;
373
380
}
374
381
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 {
376
388
if ( nodeId === this . _rootNodeId ) {
377
- return 1 ;
389
+ return count + 1 ;
378
390
}
379
391
visited = visited . concat ( nodeId ) ;
380
- let count = 0 ;
381
392
for ( const parentNodeId of this . getNodeParentsNodeIds ( nodeId ) ) {
382
393
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
+ }
384
398
}
385
399
}
386
400
return count ;
0 commit comments