Last active
November 2, 2021 23:51
-
-
Save ngarbezza/a2b7f58846aa1632e2cc4fc77427e3a0 to your computer and use it in GitHub Desktop.
A simple refactoring for JS made with Acorn (https://github.com/acornjs/acorn)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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