Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Allow findAllNodes callback to return generic AST nodes #1220

Merged
merged 1 commit into from Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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