/
arrow-function-arguments.js
84 lines (74 loc) · 2.18 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
83
84
// -----------------------------------------------------------------------------
// Update arrow function arguments to args
function arrowFunctionArguments(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) => {
const arrow = j.arrowFunctionExpression(
(fn.params || []).concat(
// https://github.com/benjamn/recast/pull/179
// j.spreadElementPattern(args)
),
fn.body,
fn.generator
);
arrow.rest = args;
return arrow;
};
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 args = fn.rest || 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(filterArrowFunctions)
.forEach(updateArgumentsCalls)
.size() > 0;
return didTransform ? root.toSource(printOptions) + '\n' : null;
}
module.exports = arrowFunctionArguments;