Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
Traversing an AST callback when finished?

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.

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!