Skip to content

Commit 83e8d18

Browse files
committed
TypescriptAPIUtils: add findNodesByType function
1 parent 3a59666 commit 83e8d18

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './findNode';
22
export * from './findLastNodeOfType';
3+
export * from './findNodesByType';
34
export * from './lookupSourceFile';
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
});

0 commit comments

Comments
 (0)