Skip to content

Instantly share code, notes, and snippets.

@zwilias
Created October 31, 2017 13:13
Show Gist options
  • Save zwilias/878647b2e817ddd9552672bbd6cf13ab to your computer and use it in GitHub Desktop.
Save zwilias/878647b2e817ddd9552672bbd6cf13ab to your computer and use it in GitHub Desktop.
Codeshift transformation to eliminate redundant A* calls (i.e. where the number of arguments matches the arity of the function)
module.exports = function(fileInfo, api, options) {
var source = fileInfo.source,
shift = api.jscodeshift,
shiftSource = shift(fileInfo.source);
var functionMakers = ["F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"];
var functionCallers = ["A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"];
var arities = {};
shiftSource
.find(shift.VariableDeclarator)
.filter(function(path) {
return (
path.value.init &&
path.value.init.type === "CallExpression" &&
functionMakers.indexOf(path.value.init.callee.name) !== -1
);
})
.forEach(function(path) {
arities[path.value.id.name] =
functionMakers.indexOf(path.value.init.callee.name) + 2;
});
return shiftSource
.find(shift.CallExpression)
.filter(function(path) {
var calledFunction, specifiedArity;
return (
functionCallers.indexOf(path.value.callee.name) !== -1 &&
(calledFunction = path.value.arguments[0].name) &&
(specifiedArity = arities[calledFunction]) &&
specifiedArity == path.value.arguments.length - 1
);
})
.map(function(path) {
var args = path.value.arguments;
var calledFunction = args.shift();
return path.replace(
shift.callExpression(
shift.memberExpression(
calledFunction,
shift.identifier("func")
),
args
)
);
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment