forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildOptimizedSequenceExpression.js
56 lines (46 loc) · 1.56 KB
/
buildOptimizedSequenceExpression.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
import { types as t } from "@babel/core";
// tries to optimize sequence expressions in the format
// (a = b, ((c) => d + e)(a))
// to
// (a = b, a + e)
const buildOptimizedSequenceExpression = ({ assign, call, path }) => {
const { left: placeholderNode, right: pipelineLeft } = assign;
const { callee: pipelineRight } = call;
let optimizeArrow =
t.isArrowFunctionExpression(pipelineRight) &&
t.isExpression(pipelineRight.body) &&
!pipelineRight.async &&
!pipelineRight.generator;
let param;
if (optimizeArrow) {
const { params } = pipelineRight;
if (params.length === 1 && t.isIdentifier(params[0])) {
param = params[0];
} else if (params.length > 0) {
optimizeArrow = false;
}
} else if (t.isIdentifier(pipelineRight, { name: "eval" })) {
const evalSequence = t.sequenceExpression([
t.numericLiteral(0),
pipelineRight,
]);
call.callee = evalSequence;
return t.sequenceExpression([assign, call]);
} else if (
(t.isIdentifier(pipelineRight) &&
path.scope.hasBinding(pipelineRight.name)) ||
t.isImmutable(pipelineLeft)
) {
return t.callExpression(pipelineRight, [pipelineLeft]);
}
if (optimizeArrow && !param) {
// Arrow function with 0 arguments
return t.sequenceExpression([pipelineLeft, pipelineRight.body]);
}
if (param) {
path.get("right").scope.rename(param.name, placeholderNode.name);
return t.sequenceExpression([assign, pipelineRight.body]);
}
return t.sequenceExpression([assign, call]);
};
export default buildOptimizedSequenceExpression;