File tree Expand file tree Collapse file tree 3 files changed +50
-0
lines changed
packages/typescript-api-utils Expand file tree Collapse file tree 3 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ import * as ts from 'typescript' ;
2+
3+
4+ export function findNodesByType < T extends ts . Node > ( kind : ts . SyntaxKind , sourceFile : ts . SourceFile ) : Array < T >
5+ {
6+ const nodes : Array < T > = [ ] ;
7+
8+ function findLoop ( parent : ts . Node ) : void
9+ {
10+ ts . forEachChild ( parent , ( child : ts . Node ) => {
11+ if ( child . kind === kind ) {
12+ nodes . push ( < T > child ) ;
13+ }
14+
15+ findLoop ( child ) ;
16+ } ) ;
17+ }
18+
19+ findLoop ( sourceFile ) ;
20+
21+ return nodes ;
22+ }
Original file line number Diff line number Diff line change 11export * from './findNode' ;
22export * from './findLastNodeOfType' ;
3+ export * from './findNodesByType' ;
34export * from './lookupSourceFile' ;
Original file line number Diff line number Diff line change 1+ import { findNodesByType } from '../../../' ;
2+ import { expect } from 'chai' ;
3+ import * as ts from 'typescript' ;
4+
5+
6+ describe ( '#sourceFiles/findNodesByType' , ( ) => {
7+
8+ describe ( 'findNodesByType()' , ( ) => {
9+
10+ it ( 'should return all nodes by type' , ( ) => {
11+ const sourceFile = < ts . SourceFile > ts . createSourceFile (
12+ '/main.ts' ,
13+ 'const a = 1; const b = 2;' ,
14+ ts . ScriptTarget . Latest
15+ ) ;
16+
17+ const nodes = findNodesByType < ts . Identifier > ( ts . SyntaxKind . Identifier , sourceFile ) ;
18+
19+ console . log ( nodes ) ;
20+ expect ( nodes . length ) . to . be . equal ( 2 ) ;
21+ expect ( nodes [ 0 ] . text ) . to . be . equal ( 'a' ) ;
22+ expect ( nodes [ 1 ] . text ) . to . be . equal ( 'b' ) ;
23+ } ) ;
24+
25+ } ) ;
26+
27+ } ) ;
You can’t perform that action at this time.
0 commit comments