Skip to content

Instantly share code, notes, and snippets.

@andrey-skl
Last active December 14, 2016 18:30
Show Gist options
  • Save andrey-skl/fb13ad432c22c89057c9d0722ee6d904 to your computer and use it in GitHub Desktop.
Save andrey-skl/fb13ad432c22c89057c9d0722ee6d904 to your computer and use it in GitHub Desktop.
Converts arrow functions, mistakely used for controllers, factories and services, to normal function expressions. Example usage http://astexplorer.net/#/4JAWwc4Jmf/1
//Usage: jscodeshift -t angular-arrows-to-fns.js <pathes to files>
var THING_TO_REPLACE = 'controller';
module.exports = (file, api, options) => {
const j = api.jscodeshift;
const root = j(file.source);
return root
.find(j.ArrowFunctionExpression)
.filter(path => {
const isArgument = path.parentPath.name === 'arguments' && path.parentPath.value.indexOf(path.value) > -1;
if (!isArgument) {
return false;
}
const caller = path.parentPath
&& path.parentPath.parentPath
&& path.parentPath.parentPath.value.callee
&& path.parentPath.parentPath.value.callee.property
&& path.parentPath.parentPath.value.callee.property.name;
const isArgumentOfAngularStuff = path.parentPath.value[0].type === "Literal"
&& path.parentPath.value[1].type === "ArrowFunctionExpression"
&& caller === THING_TO_REPLACE;
return isArgument && isArgumentOfAngularStuff;
})
.replaceWith(p => {
var body = p.value.body;
if (body.type !== 'BlockStatement') {
body = j.blockStatement([j.returnStatement(body)]);
}
//console.log(p.value.params)
return j.functionExpression(j.identifier(THING_TO_REPLACE), p.value.params, body);
}).
toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment