Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is a non-working codemod that tried to refactor specific functions with multiple parameters into a single object with destructuring. It failed.
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
You can’t perform that action at this time.