/
object-collapser.js
58 lines (47 loc) · 1.25 KB
/
object-collapser.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
"use strict";
const Collapser = require("./collapser");
class ObjectCollapser extends Collapser {
isInitTypeValid(init) {
return init.isObjectExpression();
}
isExpressionTypeValid(expr) {
return expr.isAssignmentExpression();
}
getExpressionChecker(objName, checkReference) {
return expr => {
// checks expr is of form:
// foo.a = rval | foo[a] = rval
const left = expr.get("left");
if (!left.isMemberExpression()) {
return false;
}
const obj = left.get("object"),
prop = left.get("property");
if (!obj.isIdentifier() || obj.node.name !== objName) {
return false;
}
if (!prop.isIdentifier() && checkReference(prop)) {
return false;
}
if (
left.node.computed &&
!(prop.isStringLiteral() || prop.isNumericLiteral())
) {
return false;
}
const right = expr.get("right");
if (checkReference(right)) {
return false;
}
return true;
};
}
extractAssignment(expr) {
return [expr.node.left.property, expr.node.right];
}
addSuccessfully(t, [left, right], init) {
init.properties.push(t.objectProperty(left, right));
return true;
}
}
module.exports = ObjectCollapser;