-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.ts
66 lines (65 loc) 路 1.84 KB
/
index.ts
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
import {
callExpression,
identifier,
isIdentifier,
isSpreadElement,
memberExpression,
optionalCallExpression,
optionalMemberExpression,
} from "@babel/types";
import type {
CallExpression,
Expression,
OptionalCallExpression,
} from "@babel/types";
/**
* A helper function that generates a new call expression with given thisNode.
It will also optimize `(...arguments)` to `.apply(arguments)`
*
* @export
* @param {Expression} callee The callee of call expression
* @param {Expression} thisNode The desired this of call expression
* @param {Readonly<CallExpression["arguments"]>} args The arguments of call expression
* @param {boolean} optional Whether the call expression is optional
* @returns {CallExpression | OptionalCallExpression} The generated new call expression
*/
export default function optimiseCallExpression(
callee: Expression,
thisNode: Expression,
args: Readonly<CallExpression["arguments"]>,
optional: boolean,
): CallExpression | OptionalCallExpression {
if (
args.length === 1 &&
isSpreadElement(args[0]) &&
isIdentifier(args[0].argument, { name: "arguments" })
) {
// a.b?.(...arguments);
if (optional) {
return optionalCallExpression(
optionalMemberExpression(callee, identifier("apply"), false, true),
[thisNode, args[0].argument],
false,
);
}
// a.b(...arguments);
return callExpression(memberExpression(callee, identifier("apply")), [
thisNode,
args[0].argument,
]);
} else {
// a.b?.(arg1, arg2)
if (optional) {
return optionalCallExpression(
optionalMemberExpression(callee, identifier("call"), false, true),
[thisNode, ...args],
false,
);
}
// a.b(arg1, arg2)
return callExpression(memberExpression(callee, identifier("call")), [
thisNode,
...args,
]);
}
}