I have an AST created by babelParser. I want to traverse the nodes to create an array of nodes that match a certain criteria. The problem I seem to have is knowing when the traversing as reached its final point. The code would look something like this...
traverseNodes(ast, () => {
// some act on each node that adds it to an array
}.then((arrayOfMatchNodes) => {
// some action when ALL nodes have been handled.
}
What module could I use 'traverseNodes' here? Every example I have seen of traversing nodes, doesn't seem to have a callback for when its actually finished.
Traverse is synchronous so when it's done next code will be executed.
import parser from "@babel/parser";
import traverse from "@babel/traverse";
const code = `function square(n) {
return n * n;
}`;
const ast = parser.parse(code);
const nodes = [];
traverse(ast, {
Identifier(path) {
nodes.push(path);
}
});
// show all the nodes
console.log(nodes);
You can achieve it even simpler with help of my library 🐊Putout (no need to use parse and traverse):
import putout from 'putout';
const source = `function square(n) {
return n * n;
}`;
const nodes = [];
putout(source, {
plugins: [
['collect', {
report: () => 'collect nodes',
fix: (path) => nodes.push(path),
include: () => [
'Identifier'
]
}]
]
});
console.log(nodes);
You can find more information about traversing and working with AST in Babel Handbook.