Skip to content

Commit 120b4b8

Browse files
authored
Merge pull request #1220 from Quramy/find_all_nodes
chore: Allow findAllNodes callback to return generic AST nodes
2 parents d65f31e + ba7c278 commit 120b4b8

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/ts-ast-util/utilily-functions.test.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ describe(isTagged, () => {
3030
});
3131

3232
describe(findAllNodes, () => {
33-
it('findAllNodes should return nodes which match given condition', () => {
33+
it('should return nodes which match given condition', () => {
3434
// prettier-ignore
3535
const text = 'const a = `AAA`;' + '\n'
3636
+ 'const b = `BBB`;';
@@ -39,6 +39,18 @@ describe(findAllNodes, () => {
3939
expect(actual.length).toBe(2);
4040
expect(actual.map(n => n.getText())).toEqual(['`AAA`', '`BBB`']);
4141
});
42+
43+
it('should accepts callback which returns ts.Node', () => {
44+
const text = `
45+
const a = fn(\`AAA\`);
46+
const b = fn('BBB');
47+
`;
48+
const s = ts.createSourceFile('input.ts', text, ts.ScriptTarget.Latest);
49+
const actual = findAllNodes(s, node => (ts.isCallExpression(node) ? node.arguments[0] : undefined));
50+
expect(actual.length).toBe(2);
51+
expect(ts.isNoSubstitutionTemplateLiteral(actual[0])).toBeTruthy();
52+
expect(ts.isStringLiteral(actual[1])).toBeTruthy();
53+
});
4254
});
4355

4456
describe(isImportDeclarationWithCondition, () => {

src/ts-ast-util/utilily-functions.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,18 +48,22 @@ export function findNode(sourceFile: ts.SourceFile, position: number): ts.Node |
4848
return find(sourceFile);
4949
}
5050

51-
export function findAllNodes(sourceFile: ts.SourceFile, cond: (n: ts.Node) => boolean): ts.Node[] {
52-
const result: ts.Node[] = [];
51+
export function findAllNodes<S extends ts.Node>(
52+
sourceFile: ts.SourceFile,
53+
cond: (n: ts.Node) => S | boolean | undefined,
54+
): S[] {
55+
const result: (S | ts.Node)[] = [];
5356
function find(node: ts.Node) {
54-
if (cond(node)) {
55-
result.push(node);
57+
const hit = cond(node);
58+
if (hit) {
59+
result.push(hit === true ? node : hit);
5660
return;
5761
} else {
5862
ts.forEachChild(node, find);
5963
}
6064
}
6165
find(sourceFile);
62-
return result;
66+
return result as S[];
6367
}
6468

6569
export function hasTagged(node: ts.Node | undefined, condition: TagCondition) {

0 commit comments

Comments
 (0)