Created
September 21, 2016 11:05
-
-
Save dagingaa/433972a7494c83e3f7db7a9e2394e032 to your computer and use it in GitHub Desktop.
This is a non-working codemod that tried to refactor specific functions with multiple parameters into a single object with destructuring. It failed.
This file contains hidden or 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
export default function transformer(file, api) { | |
const j = api.jscodeshift; | |
const name = "subscribeToPlan"; | |
const newName = name; | |
const root = j(file.source); | |
root | |
.find(j.MethodDefinition) | |
.filter(path => !!path.value.key.name) | |
.filter(path => path.value.key.name === name) | |
.filter(path => path.value.value.params.length > 1) | |
.forEach(path => { | |
function createObjectPattern() { | |
const obj = j.objectPattern( | |
path.value.value.params.map(param => { | |
const prop = j.property("init", param, param) | |
prop.shorthand = true; | |
return prop | |
}) | |
) | |
obj.loc = null; | |
return obj; | |
} | |
function createExpression() { | |
const func = j.functionExpression( | |
null, | |
[createObjectPattern()], | |
path.value.value.body | |
) | |
func.loc = null; | |
return func; | |
} | |
j(path).replaceWith( | |
j.methodDefinition( | |
"method", | |
j.identifier(newName), | |
createExpression() | |
) | |
); | |
}); | |
root | |
.find(j.CallExpression) | |
.filter(path => path.value.callee.property) | |
.filter(path => path.value.callee.property.name === name) | |
.filter(path => path.value.arguments.length > 1) | |
.forEach(path => { | |
j(path).replaceWith( | |
j.callExpression( | |
j.memberExpression( | |
path.value.callee.object, | |
j.identifier(newName) | |
), | |
[ | |
j.objectExpression( | |
path.value.arguments.map(param => { | |
const prop = j.property("init", param, param) | |
if (prop.value.type === "Identifier") { | |
prop.shorthand = true; | |
} else { | |
prop.key = j.identifier(prop.value.property.name) | |
} | |
return prop | |
}) | |
) | |
] | |
) | |
) | |
}) | |
return root.toSource() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment