sarsamurmu / estree-toolkit

Tools for working with ESTree AST
https://estree-toolkit.netlify.app/
MIT License
54 stars 1 forks source link

Question on how to construct NodePaths #7

Closed not-jan closed 1 year ago

not-jan commented 1 year ago

I'm trying to simplify a piece of code. The code looks like this:

if (true) {
  console.log("true");
else {
  console.log("false");
}

The easiest way of implementing this would be to use the evaluateTruthy function from the utilities but that will only take a path. Is there any way of reusing that code for my purposes?

sarsamurmu commented 1 year ago

Sadly, it can't use anything other than nodepaths

Here is an MVP example to do this (if you have some confusions)

const { traverse, utils: u } = require('estree-toolkit')
const { parseModule } = require('meriyah')
const { generate } = require('astring')

const ast = parseModule(`
if (true) {
  console.log("true");
} else {
  console.log("false");
}
`)

traverse(ast, {
  IfStatement(path) {
    const res = u.evaluateTruthy(path.get('test'))
    if (res != null) {
      if (res) {
        path.replaceWith(structuredClone(path.get('consequent').node))
      } else {
        path.replaceWith(structuredClone(path.get('alternate').node))
      }
    }
  }
})

console.log('---------------')
console.log(generate(ast))
not-jan commented 1 year ago

Thank you! :)

sarsamurmu commented 1 year ago

I was using consequent instead of alternate in else. I updated the code to fix that.