-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.js
More file actions
65 lines (61 loc) · 1.91 KB
/
encoder.js
File metadata and controls
65 lines (61 loc) · 1.91 KB
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
exports.__encode = (config, value, pretty) => {
const eson_encoded_data = eson_encode(config, value)
if (pretty) return JSON.stringify(eson_encoded_data, null, 4)
return JSON.stringify(eson_encoded_data)
}
const eson_encode = (config, value) => {
if (Array.isArray(value)) {
const eson_list = []
return value.map(element => {
let [encoded_key, encoded_value] = eson_encode_type(
config,
"",
element
)
if (encoded_key) {
const encoded_object = {}
encoded_object[encoded_key] = encoded_value
return encoded_object
}
return encoded_value
})
}
if (value && value.constructor === Object) {
const eson_data = {}
Object.entries(value).forEach(([key, value]) => {
let [encoded_key, encoded_value] = eson_encode_type(
config,
key,
value
)
eson_data[encoded_key] = encoded_value
})
return eson_data
}
let [encoded_key, encoded_value] = eson_encode_type(config, "", value)
if (encoded_key) {
const encoded_object = {}
encoded_object[encoded_key] = encoded_value
return encoded_object
}
return encoded_value
}
const eson_encode_type = (config, key, value) => {
let [encoded_key, encoded_value] = [key, value]
let name
for (name in config) {
const extension = config[name]
if (extension.should_encode(value)) {
encoded_key = `${extension.name}~${key}`
encoded_value = extension.encode(value)
break
}
}
if (
encoded_value &&
(Array.isArray(encoded_value) || encoded_value.constructor == Object)
) {
encoded_value = eson_encode(config, encoded_value)
}
return [encoded_key, encoded_value]
}