Skip to content

Instantly share code, notes, and snippets.

@ngarbezza
Last active November 2, 2021 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngarbezza/a2b7f58846aa1632e2cc4fc77427e3a0 to your computer and use it in GitHub Desktop.
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 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