@@ -10,22 +10,27 @@ import type { GetPointerPriorityFn, WalkFn } from './types/walk';
1010const walkDeclarations : WalkFn = ( graph , callback , options ) => {
1111 if ( options ?. preferGroups && options . preferGroups . length ) {
1212 // Single pass: bucket each pointer into its group (or unmatched).
13- // This avoids re-scanning all pointers K times (once per preferred group).
13+ // A Set of preferGroups provides O(1) membership check; buckets are created
14+ // lazily on first match so no separate pre-init loop is needed.
15+ const preferGroupsSet = new Set ( options . preferGroups ) ;
1416 const buckets = new Map < string , string [ ] > ( ) ;
15- for ( const kind of options . preferGroups ) {
16- if ( ! buckets . has ( kind ) ) {
17- buckets . set ( kind , [ ] ) ;
18- }
19- }
2017 const unmatched : string [ ] = [ ] ;
2118
2219 for ( const pointer of graph . nodes . keys ( ) ) {
2320 if ( options . matchPointerToGroup ) {
2421 const result = options . matchPointerToGroup ( pointer ) ;
2522 if ( result . matched ) {
26- const bucket = buckets . get ( result . kind ) ;
27- // kind not in preferGroups → treat as unmatched
28- ( bucket ?? unmatched ) . push ( pointer ) ;
23+ if ( preferGroupsSet . has ( result . kind ) ) {
24+ let bucket = buckets . get ( result . kind ) ;
25+ if ( ! bucket ) {
26+ bucket = [ ] ;
27+ buckets . set ( result . kind , bucket ) ;
28+ }
29+ bucket . push ( pointer ) ;
30+ } else {
31+ // kind not in preferGroups → treat as unmatched
32+ unmatched . push ( pointer ) ;
33+ }
2934 continue ;
3035 }
3136 }
@@ -37,8 +42,11 @@ const walkDeclarations: WalkFn = (graph, callback, options) => {
3742 for ( const kind of options . preferGroups ) {
3843 if ( emittedGroups . has ( kind ) ) continue ;
3944 emittedGroups . add ( kind ) ;
40- for ( const pointer of buckets . get ( kind ) ! ) {
41- callback ( pointer , graph . nodes . get ( pointer ) ! ) ;
45+ const pointers = buckets . get ( kind ) ;
46+ if ( pointers ) {
47+ for ( const pointer of pointers ) {
48+ callback ( pointer , graph . nodes . get ( pointer ) ! ) ;
49+ }
4250 }
4351 }
4452 for ( const pointer of unmatched ) {
0 commit comments