forked from nicoespeon/abracadabra
/
simplify-ternary.ts
87 lines (78 loc) · 2.28 KB
/
simplify-ternary.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Editor, Code, ErrorReason } from "../../editor/editor";
import { Selection } from "../../editor/selection";
import * as t from "../../ast";
export { simplifyTernary, createVisitor as createTernaryToSimplifyVisitor };
async function simplifyTernary(
code: Code,
selection: Selection,
editor: Editor
) {
const updatedCode = updateCode(t.parse(code), selection);
if (!updatedCode.hasCodeChanged) {
editor.showError(ErrorReason.DidNotFoundTernaryToSimplify);
return;
}
await editor.write(updatedCode.code);
}
function updateCode(ast: t.AST, selection: Selection): t.Transformed {
return t.transformAST(
ast,
createVisitor(selection, (path, convertedNode) =>
path.replaceWith(convertedNode)
)
);
}
function createVisitor(
selection: Selection,
onMatch: (
path: t.NodePath<t.ConditionalExpression>,
convertedNode: t.Node
) => void
): t.Visitor {
return {
ConditionalExpression(path) {
if (!selection.isInsidePath(path)) return;
if (t.isBooleanLiteral(path.node.test)) {
// bool ? a : b
if (path.node.test.value) {
onMatch(path, path.node.consequent);
} else {
onMatch(path, path.node.alternate);
}
} else if (
t.isBooleanLiteral(path.node.consequent) &&
t.isBooleanLiteral(path.node.alternate)
) {
// a ? bool : bool
const consequentValue = path.node.consequent.value;
const alternateValue = path.node.alternate.value;
if (consequentValue) {
if (alternateValue) {
// a ? true : true
onMatch(path, t.booleanLiteral(true));
} else {
// a ? true : false
onMatch(
path,
t.callExpression(t.identifier("Boolean"), [path.node.test])
);
}
} else {
if (alternateValue) {
// a ? false : true
onMatch(path, t.unaryExpression("!", path.node.test));
} else {
onMatch(path, t.booleanLiteral(false));
}
}
} else if (t.areEqual(path.node.test, path.node.consequent)) {
// a ? a : b
onMatch(
path,
t.logicalExpression("||", path.node.test, path.node.alternate)
);
}
path.stop();
}
};
}