-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
53 lines (45 loc) · 1.03 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
const t = require('@babel/types')
const easyPeasies = ['BooleanLiteral', 'StringLiteral', 'NumericLiteral']
function toJs(node) {
if (easyPeasies.includes(node.type)) {
return node.value
}
if (node.name === 'undefined' && !node.value) {
return undefined
}
if (t.isNullLiteral(node)) {
return null
}
if (t.isObjectExpression(node)) {
return computeProps(node.properties)
}
if (t.isArrayExpression(node)) {
return node.elements.reduce((acc, element) =>
[
...acc,
...element.type === 'SpreadElement' ? toJs(element.argument) : [toJs(element)]
],
[],
)
}
}
function computeProps(props) {
return props.reduce((acc, prop) => {
if (prop.type === 'SpreadElement') {
return {
...acc,
...toJs(prop.argument),
}
} else if (prop.type !== 'ObjectMethod') {
const val = toJs(prop.value)
if (val !== undefined) {
return {
...acc,
[prop.key.name]: val
}
}
}
return acc
}, {})
}
module.exports = toJs