48 lines
1012 B
TypeScript

import ts = require('typescript');
import {RemoveChange, Change} from './change';
/**
* Find all nodes from the AST in the subtree of node of SyntaxKind kind.
* @param node
* @param kind
* @param max The maximum number of items to return.
* @return all nodes of kind, or [] if none is found
*/
export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max: number = Infinity): ts.Node[] {
if (!node || max == 0) {
return [];
}
let arr: ts.Node[] = [];
if (node.kind === kind) {
arr.push(node);
max--;
}
if (max > 0) {
for (const child of node.getChildren()) {
findNodes(child, kind, max).forEach(node => {
if (max > 0) {
arr.push(node);
}
max--;
});
if (max <= 0) {
break;
}
}
}
return arr;
}
export function removeAstNode(node: ts.Node): Change {
const source = node.getSourceFile();
return new RemoveChange(
source.path,
node.getStart(source),
node.getFullText(source)
);
}