forked from yorkie/esprima-to-value
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (58 loc) · 1.47 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
'use strict';
const getObject = require('esprima-get-object');
function toValue (tree) {
if (Array.isArray(tree)) {
return tree.map(toValue);
} else {
let ret = undefined;
switch (tree.type) {
case 'Literal':
ret = tree.value;
break;
case 'ArrayExpression':
ret = tree.elements.map(toValue);
break;
case 'FunctionExpression':
ret = getReturn(tree.body.body);
break;
case 'ObjectExpression':
ret = {};
for (let prop of tree.properties) {
ret[prop.key.name || prop.key.value] = toValue(prop.value);
}
break;
case 'UnaryExpression':
if (tree.operator == '-') {
ret = -1 * toValue(tree.argument);
} else {
throw new Error('Unknown unary operator')
}
break;
case 'Program':
ret = toValue(tree.body);
break;
case 'ExpressionStatement':
ret = toValue(tree.expression);
break;
default:
throw new Error('Unsupported type: ' + tree.type);
break;
}
return ret;
}
}
function getReturn (body) {
const tree = body.shift();
if (tree.type === 'ReturnStatement') {
if (tree.argument && tree.argument.property) {
return getObject(tree.argument);
} else {
return null;
}
} else if (tree.type === 'TryStatement') {
return getReturn(tree.block.body);
} else {
return getReturn(body);
}
}
module.exports = toValue;