Skip to content

Instantly share code, notes, and snippets.

@AlexFrazer
Created May 11, 2023 20:37
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 AlexFrazer/36d733fb72ec12602aae30c42f880824 to your computer and use it in GitHub Desktop.
Save AlexFrazer/36d733fb72ec12602aae30c42f880824 to your computer and use it in GitHub Desktop.
Restructure props
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
return j(fileInfo.source)
.find(j.FunctionDeclaration)
.forEach((path) => {
const params = path.value.params;
if (params.length === 1 && params[0].type === "Identifier" && params[0].name === "props") {
const propsParam = params[0];
const propsUsages = j(path).find(j.Identifier, { name: "props" });
const propsNames = new Set();
propsUsages.forEach((propsPath) => {
if (
propsPath.parentPath.value.type === "MemberExpression" &&
propsPath.parentPath.value.object === propsPath.value
) {
propsNames.add(propsPath.parentPath.value.property.name);
propsPath.parentPath.replace(propsPath.parentPath.value.property);
}
});
propsParam.type = "ObjectPattern";
propsParam.properties = Array.from(propsNames).map((name) =>
j.property("init", j.identifier(name), j.identifier(name))
);
}
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment