This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 126
/
ast-utils.js
98 lines (74 loc) · 2.05 KB
/
ast-utils.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
export { default as isReference } from 'is-reference';
export function flatten(node) {
const parts = [];
while (node.type === 'MemberExpression') {
if (node.computed) return null;
parts.unshift(node.property.name);
node = node.object;
}
if (node.type !== 'Identifier') return null;
const name = node.name;
parts.unshift(name);
return { name, keypath: parts.join('.') };
}
export function extractNames(node) {
const names = [];
extractors[node.type](names, node);
return names;
}
function getExtractor (type) {
const extractor = extractors[type];
if (!extractor)
throw new SyntaxError(`${type} pattern not supported.`);
return extractor;
}
const extractors = {
Identifier(names, node) {
names.push(node.name);
},
ObjectPattern(names, node) {
node.properties.forEach(prop => {
getExtractor(prop.value.type)(names, prop.value);
});
},
ArrayPattern(names, node) {
node.elements.forEach(element => {
if (!element) return;
getExtractor(element.type)(names, element);
});
},
RestElement(names, node) {
getExtractor(node.argument.type)(names, node.argument);
},
AssignmentPattern(names, node) {
getExtractor(node.left.type)(names, node.left);
}
};
export function isTruthy(node) {
if (node.type === 'Literal') return !!node.value;
if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
if (node.operator in operators) return operators[node.operator](node);
}
export function isFalsy(node) {
return not(isTruthy(node));
}
function not(value) {
return value === undefined ? value : !value;
}
function equals(a, b, strict) {
if (a.type !== b.type) return undefined;
if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
}
const operators = {
'==': x => {
return equals(x.left, x.right, false);
},
'!=': x => not(operators['=='](x)),
'===': x => {
return equals(x.left, x.right, true);
},
'!==': x => not(operators['==='](x)),
'!': x => isFalsy(x.argument),
'&&': x => isTruthy(x.left) && isTruthy(x.right),
'||': x => isTruthy(x.left) || isTruthy(x.right)
};