Skip to content

Commit

Permalink
Merge pull request #1220 from Quramy/find_all_nodes
Browse files Browse the repository at this point in the history
chore: Allow findAllNodes callback to return generic AST nodes
  • Loading branch information
Quramy committed Mar 13, 2024
2 parents d65f31e + ba7c278 commit 120b4b8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
14 changes: 13 additions & 1 deletion src/ts-ast-util/utilily-functions.test.ts
Expand Up @@ -30,7 +30,7 @@ describe(isTagged, () => {
});

describe(findAllNodes, () => {
it('findAllNodes should return nodes which match given condition', () => {
it('should return nodes which match given condition', () => {
// prettier-ignore
const text = 'const a = `AAA`;' + '\n'
+ 'const b = `BBB`;';
Expand All @@ -39,6 +39,18 @@ describe(findAllNodes, () => {
expect(actual.length).toBe(2);
expect(actual.map(n => n.getText())).toEqual(['`AAA`', '`BBB`']);
});

it('should accepts callback which returns ts.Node', () => {
const text = `
const a = fn(\`AAA\`);
const b = fn('BBB');
`;
const s = ts.createSourceFile('input.ts', text, ts.ScriptTarget.Latest);
const actual = findAllNodes(s, node => (ts.isCallExpression(node) ? node.arguments[0] : undefined));
expect(actual.length).toBe(2);
expect(ts.isNoSubstitutionTemplateLiteral(actual[0])).toBeTruthy();
expect(ts.isStringLiteral(actual[1])).toBeTruthy();
});
});

describe(isImportDeclarationWithCondition, () => {
Expand Down
14 changes: 9 additions & 5 deletions src/ts-ast-util/utilily-functions.ts
Expand Up @@ -48,18 +48,22 @@ export function findNode(sourceFile: ts.SourceFile, position: number): ts.Node |
return find(sourceFile);
}

export function findAllNodes(sourceFile: ts.SourceFile, cond: (n: ts.Node) => boolean): ts.Node[] {
const result: ts.Node[] = [];
export function findAllNodes<S extends ts.Node>(
sourceFile: ts.SourceFile,
cond: (n: ts.Node) => S | boolean | undefined,
): S[] {
const result: (S | ts.Node)[] = [];
function find(node: ts.Node) {
if (cond(node)) {
result.push(node);
const hit = cond(node);
if (hit) {
result.push(hit === true ? node : hit);
return;
} else {
ts.forEachChild(node, find);
}
}
find(sourceFile);
return result;
return result as S[];
}

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

0 comments on commit 120b4b8

Please sign in to comment.