Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple refactoring for JS made with Acorn (https://github.com/acornjs/acorn)
// this is our input
sourceCode = 'if (a > b) { return true } else { return false }'
// now we call the parser with the right set of options
const acorn = require('acorn')
programNode = acorn.parse(sourceCode, { ecmaVersion: 11, allowReturnOutsideFunction: true })
// validate the transformation can be made to this source code
containsOneStatement = programNode.body.length === 1
ifStatement = programNode.body[0]
thenHasASingleStatement = ifStatement.consequent.body.length === 1
elseHasASingleStatement = ifStatement.alternate.body.length === 1
thenReturnsTrue = ifStatement.consequent.body[0].argument.value === true
elseReturnsFalse = ifStatement.alternate.body[0].argument.value === false
refactoringCanBeApplied = containsOneStatement && thenHasASingleStatement && elseHasASingleStatement && thenReturnsTrue && elseReturnsFalse
// generate the new code
refactoredSourceCode = `return ${sourceCode.slice(ifStatement.test.start, ifStatement.test.end)}`
// verify the resulting code is what we expected!
expectedSourceCode = 'return a > b'
expectedSourceCode === refactoredSourceCode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment