@@ -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 ;
0 commit comments