-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathsimplifyCalls.js
30 lines (29 loc) · 1.07 KB
/
simplifyCalls.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
/**
* Remove unnecessary usage of '.call(this' or '.apply(this' when calling a function
* @param {Arborist} arb
* @param {Function} candidateFilter (optional) a filter to apply on the candidates list
* @return {Arborist}
*/
function simplifyCalls(arb, candidateFilter = () => true) {
const relevantNodes = [
...(arb.ast[0].typeMap.CallExpression || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (n.arguments?.[0]?.type === 'ThisExpression' &&
n.callee.type === 'MemberExpression' &&
['apply', 'call'].includes(n.callee.property?.name || n.callee.property?.value) &&
(n.callee.object?.name || n.callee?.value) !== 'Function' &&
!/function/i.test(n.callee.object.type) &&
candidateFilter(n)) {
const args = (n.callee.property?.name || n.callee.property?.value) === 'apply' ? n.arguments?.[1]?.elements : n.arguments?.slice(1);
arb.markNode(n, {
type: 'CallExpression',
callee: n.callee.object,
arguments: Array.isArray(args) ? args : (args ? [args] : []),
});
}
}
return arb;
}
export default simplifyCalls;