-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
valueToNode.js
93 lines (81 loc) 路 2.02 KB
/
valueToNode.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
// @flow
import isPlainObject from "lodash.isplainobject";
import isRegExp from "lodash.isregexp";
import isValidIdentifier from "../validators/isValidIdentifier";
import {
identifier,
booleanLiteral,
nullLiteral,
stringLiteral,
numericLiteral,
regExpLiteral,
arrayExpression,
objectProperty,
objectExpression,
unaryExpression,
binaryExpression,
} from "../builders/generated";
export default function valueToNode(value: any): Object {
// undefined
if (value === undefined) {
return identifier("undefined");
}
// boolean
if (value === true || value === false) {
return booleanLiteral(value);
}
// null
if (value === null) {
return nullLiteral();
}
// strings
if (typeof value === "string") {
return stringLiteral(value);
}
// numbers
if (typeof value === "number") {
let result;
if (Number.isFinite(value)) {
result = numericLiteral(Math.abs(value));
} else {
let numerator;
if (Number.isNaN(value)) {
// NaN
numerator = numericLiteral(0);
} else {
// Infinity / -Infinity
numerator = numericLiteral(1);
}
result = binaryExpression("/", numerator, numericLiteral(0));
}
if (value < 0 || Object.is(value, -0)) {
result = unaryExpression("-", result);
}
return result;
}
// regexes
if (isRegExp(value)) {
const pattern = value.source;
const flags = value.toString().match(/\/([a-z]+|)$/)[1];
return regExpLiteral(pattern, flags);
}
// array
if (Array.isArray(value)) {
return arrayExpression(value.map(valueToNode));
}
// object
if (isPlainObject(value)) {
const props = [];
for (const key of Object.keys(value)) {
let nodeKey;
if (isValidIdentifier(key)) {
nodeKey = identifier(key);
} else {
nodeKey = stringLiteral(key);
}
props.push(objectProperty(nodeKey, valueToNode(value[key])));
}
return objectExpression(props);
}
throw new Error("don't know how to turn this value into a node");
}