Closed not-jan closed 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))
Thank you! :)
I was using consequent
instead of alternate in else
. I updated the code to fix that.
I'm trying to simplify a piece of code. The code looks like this:
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?