-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyliant.js
More file actions
101 lines (94 loc) · 2.82 KB
/
pyliant.js
File metadata and controls
101 lines (94 loc) · 2.82 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
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
99
100
101
function pyliant_decode(o) {
var id_map = {}
var incomplete_refs = {}
function object_xform(o) {
if ('_ref' in o) {
if (o._ref in id_map)
return id_map[o._ref]
// add to incomplete refs and id map
incomplete_refs[o._ref] = o
id_map[o._ref] = o
delete o._ref
// will be filled in later
return o
}
if ('_id' in o) {
if (o._id in incomplete_refs) {
var ref = incomplete_refs[o._id]
// is being filled in, no longer incomplete
delete incomplete_refs[o._id]
delete o._id
for (var key in o) {
if (o[key] instanceof Array)
ref[key] = array_xform(o[key])
else if (o[key] instanceof Object)
ref[key] = object_xform(o[key])
else
ref[key] = o[key]
}
return ref
}
id_map[o._id] = o
delete o._id
}
for (var key in o) {
if (o[key] instanceof Array)
o[key] = array_xform(o[key])
else if (o[key] instanceof Object)
o[key] = object_xform(o[key])
}
return o
}
function array_xform(arr) {
var ret = []
for (var i in arr) {
if (arr[i] instanceof Array)
ret.push(array_xform(arr[i]))
else if (arr[i] instanceof Object)
ret.push(object_xform(arr[i]))
else
ret.push(arr[i])
}
return ret
}
return object_xform(o)
}
function pyliant_encode(o) {
var id_set = new WeakSet()
var id_map = new WeakMap()
var current = 1
function object_xform(o) {
if (id_map.has(o)) {
var ref = id_map.get(o)
if (!('_id' in ref))
ref._id = current++
return { _ref: ref._id }
}
var ref = {}
id_map.set(o, ref)
for (var key in o) {
if (o[key] instanceof Array)
ref[key] = array_xform(o[key])
else if (o[key] instanceof Object)
ref[key] = object_xform(o[key])
else
ref[key] = o[key]
}
return ref
}
// arrays should never be referenced multiple times
// this is reserved for object only
function array_xform(arr) {
var ret = []
for (var i in arr) {
if (arr[i] instanceof Array)
ret.push(array_xform(arr[i]))
else if (arr[i] instanceof Object)
ret.push(object_xform(arr[i]))
else
ret.push(arr[i])
}
return ret
}
return object_xform(o)
}