forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (59 loc) · 1.85 KB
/
index.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
export default function ({ types: t }) {
return {
inherits: require("babel-plugin-syntax-pipeline-operator"),
visitor: {
BinaryExpression(path) {
if (path.node.operator === "|>") {
let right = path.node.right;
if (
right.type === "ArrowFunctionExpression" &&
right.params.length === 1 &&
t.isIdentifier(right.params[0]) &&
t.isExpression(right.body)
) {
//
// Optimize away arrow function!
//
// This step converts:
// let result = arg |> x => x + x;
// To:
// let _x = arg;
// let result = arg |> x => x + x;
//
let paramName = right.params[0].name;
let placeholder = path.scope.generateUidIdentifier(paramName);
path.parentPath.insertBefore(t.variableDeclarator(placeholder, path.node.left));
//
// This step converts:
// let _x = arg;
// let result = arg |> x => x + x;
// To:
// let _x = arg;
// let result = arg |> _x => _x + _x;
//
path.get("right").scope.rename(paramName, placeholder.name);
//
// This step converts:
// let _x = arg;
// let result = arg |> _x => _x + _x;
// To:
// let _x = arg;
// let result = _x + _x;
//
path.replaceWith(right.body);
} else {
//
// Simple invocation.
//
// Converts:
// x |> obj.f;
// To:
// obj.f(x);
//
path.replaceWith(t.callExpression(path.node.right, [ path.node.left ]));
}
}
}
}
};
}