-
Notifications
You must be signed in to change notification settings - Fork 109
/
arrow-function-arguments.js
82 lines (72 loc) · 2.12 KB
/
arrow-function-arguments.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module.exports = (file, api, options) => {
const j = api.jscodeshift;
const printOptions = options.printOptions || {quote: 'single'};
const root = j(file.source);
const ARGUMENTS = 'arguments';
const ARGS = 'args';
const createArrowFunctionExpression = (fn, args) =>
j.arrowFunctionExpression(
(fn.params || []).concat(j.restElement(args)),
fn.body,
fn.generator
);
const filterMemberExpressions = path => path.parent.value.type !== "MemberExpression"
const filterArrowFunctions = path => {
while (path.parent) {
switch (path.value.type) {
case 'ArrowFunctionExpression':
if (j(path).find(j.Identifier, {name: ARGS}).size()) {
console.error(
file.path + ': arrow function uses "' + ARGS + '" already. ' +
'Please rename this identifier first.'
);
return false;
}
return true;
case 'FunctionExpression':
case 'MethodDeclaration':
case 'Function':
case 'FunctionDeclaration':
return false;
default:
break;
}
path = path.parent;
}
return false;
};
const updateArgumentsCalls = path => {
var afPath = path;
while (afPath.parent) {
if (afPath.value.type == 'ArrowFunctionExpression') {
break;
}
afPath = afPath.parent;
}
const {value: fn} = afPath;
const {params} = fn;
const param = params[params.length - 1];
var args;
if (param && param.type == 'RestElement') {
params.pop();
args = param.argument;
} else {
args = j.identifier(ARGS);
}
j(afPath).replaceWith(createArrowFunctionExpression(fn, args));
if (params.length) {
j(path).replaceWith(
j.arrayExpression(params.concat(j.spreadElement(args)))
);
} else {
j(path).replaceWith(args);
}
};
const didTransform = root
.find(j.Identifier, {name: ARGUMENTS})
.filter(filterMemberExpressions)
.filter(filterArrowFunctions)
.forEach(updateArgumentsCalls)
.size() > 0;
return didTransform ? root.toSource(printOptions) : null;
};