forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maybeOptimizePipelineSequence.js
51 lines (44 loc) · 1.43 KB
/
maybeOptimizePipelineSequence.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
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 maybeOptimizePipelineSequence = path => {
const [assignNode, callNode] = path.node.expressions;
const { left: placeholderNode, right: pipelineLeft } = assignNode;
const { callee: calledExpression } = callNode;
let optimizeArrow =
t.isArrowFunctionExpression(calledExpression) &&
t.isExpression(calledExpression.body) &&
!calledExpression.async &&
!calledExpression.generator;
let param;
if (optimizeArrow) {
const { params } = calledExpression;
if (params.length === 1 && t.isIdentifier(params[0])) {
param = params[0];
} else if (params.length > 0) {
optimizeArrow = false;
}
} else if (t.isIdentifier(calledExpression, { name: "eval" })) {
const evalSequence = t.sequenceExpression([
t.numericLiteral(0),
calledExpression,
]);
path.get("expressions.1.callee").replaceWith(evalSequence);
}
if (optimizeArrow && !param) {
// Arrow function with 0 arguments
path.replaceWith(
t.sequenceExpression([pipelineLeft, calledExpression.body]),
);
return;
}
if (param) {
path
.get("expressions.1.callee.body")
.scope.rename(param.name, placeholderNode.name);
path.get("expressions.1").replaceWith(calledExpression.body);
}
};
export default maybeOptimizePipelineSequence;