@@ -331,8 +331,7 @@ export function getTokens(
331331 debugAssertIsNonNull ( comments ) ;
332332
333333 // Maximum number of tokens to return
334- const count =
335- typeof countOptions === "object" && countOptions !== null ? countOptions . count : null ;
334+ let count = typeof countOptions === "object" && countOptions !== null ? countOptions . count : null ;
336335
337336 // Number of preceding tokens to additionally return
338337 const beforeCount = typeof countOptions === "number" ? countOptions : 0 ;
@@ -397,16 +396,33 @@ export function getTokens(
397396 }
398397
399398 sliceStart = max ( 0 , sliceStart - beforeCount ) ;
400- sliceEnd += afterCount ;
399+ sliceEnd = min ( sliceEnd + afterCount , tokensLength ) ;
400+
401+ if ( typeof filter !== "function" ) {
402+ return nodeTokens . slice ( sliceStart , sliceEnd ) ;
403+ }
401404
402- nodeTokens = nodeTokens . slice ( sliceStart , sliceEnd ) ;
405+ const allTokens : Token [ ] = [ ] ;
403406
404- // Filter before limiting by `count`
405- if ( filter ) nodeTokens = nodeTokens . filter ( filter ) ;
406- if ( typeof count === "number" && count < nodeTokens . length )
407- nodeTokens = nodeTokens . slice ( 0 , count ) ;
407+ if ( typeof count !== "number" ) {
408+ for ( let i = sliceStart ; i < sliceEnd ; i ++ ) {
409+ const token = nodeTokens [ i ] ;
410+ if ( filter ( token ) ) {
411+ allTokens . push ( token ) ;
412+ }
413+ }
414+ return allTokens ;
415+ }
416+
417+ for ( let i = sliceStart ; i < sliceEnd && count > 0 ; i ++ ) {
418+ const token = nodeTokens [ i ] ;
419+ if ( filter ( token ) ) {
420+ allTokens . push ( token ) ;
421+ count -- ;
422+ }
423+ }
408424
409- return nodeTokens ;
425+ return allTokens ;
410426}
411427
412428/**
0 commit comments