Skip to content

Commit 3a59666

Browse files
committed
TypescriptAPIUtils: add findLastNodeOfType function
1 parent 5f260a9 commit 3a59666

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-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 findLastNodeOfType<T extends ts.Node>(kind: ts.SyntaxKind, sourceFile: ts.SourceFile): T|undefined
5+
{
6+
let lastNode: T = undefined;
7+
8+
function findLoop(parent: ts.Node): void
9+
{
10+
ts.forEachChild(parent, (child: ts.Node) => {
11+
if (child.kind === kind) {
12+
lastNode = <T>child;
13+
}
14+
15+
findLoop(child);
16+
});
17+
}
18+
19+
findLoop(sourceFile);
20+
21+
return lastNode;
22+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './findNode';
2+
export * from './findLastNodeOfType';
23
export * from './lookupSourceFile';
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import {findLastNodeOfType} from '../../../';
2+
import {expect} from 'chai';
3+
import * as ts from 'typescript';
4+
5+
6+
describe('#sourceFiles/findLastNodeOfType', () => {
7+
8+
describe('findLastNodeOfType()', () => {
9+
10+
it('should return undefined if node does not exists', () => {
11+
const sourceFile = <ts.SourceFile>ts.createSourceFile('/main.ts', '', ts.ScriptTarget.Latest);
12+
13+
expect(findLastNodeOfType<ts.ClassDeclaration>(ts.SyntaxKind.ClassDeclaration, sourceFile)).to.be.equal(undefined);
14+
});
15+
16+
it('should return node', () => {
17+
const sourceFile = <ts.SourceFile>ts.createSourceFile(
18+
'/main.ts',
19+
'function() {const a = 1; const b = 2;}',
20+
ts.ScriptTarget.Latest
21+
);
22+
23+
const node = findLastNodeOfType<ts.Identifier>(ts.SyntaxKind.Identifier, sourceFile);
24+
25+
expect(node.kind).to.be.equal(ts.SyntaxKind.Identifier);
26+
expect(node.text).to.be.equal('b');
27+
});
28+
29+
});
30+
31+
});

0 commit comments

Comments
 (0)