-
Notifications
You must be signed in to change notification settings - Fork 18
/
json.ts
65 lines (62 loc) · 2.17 KB
/
json.ts
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
namespace microcode {
function ruleDefnFromJson(obj: any): RuleDefn {
const extractField = (t: string) => (s: string) => {
let hasField = s.indexOf("(")
if (hasField >= 0) {
const elem = s.substr(0, hasField)
if (Object.keys(tilesDB[t]).indexOf(elem) >= 0) {
const tile = tilesDB[t][elem]
const field = tile.fieldEditor.deserialize(
s.substr(hasField + 1, s.length - 2 - hasField)
)
const newOne = tile.getNewInstance(field)
return newOne
} else {
return undefined
}
} else {
return Object.keys(tilesDB[t]).indexOf(s) >= 0
? tilesDB[t][s]
: undefined
}
}
const defn = new RuleDefn()
const parseTile = (single: string, name: string) => {
if (Array.isArray(obj[single])) {
const tiles: any[] = obj[single]
return <any>tiles.map(extractField(name)).filter(t => !!t)
}
return []
}
if (typeof obj === "string") {
obj = JSON.parse(obj)
}
defn.sensors = parseTile("S", "sensors")
defn.actuators = parseTile("A", "actuators")
defn.filters = parseTile("F", "filters")
defn.modifiers = parseTile("M", "modifiers")
return defn
}
function pageDefnFromJson(obj: any): PageDefn {
if (typeof obj === "string") {
obj = JSON.parse(obj)
}
const defn = new PageDefn()
if (Array.isArray(obj["R"])) {
const rules: any[] = obj["R"]
defn.rules = rules.map(ruleDefnFromJson)
}
return defn
}
function progDefnFromJson(obj: any): ProgramDefn {
if (typeof obj === "string") {
obj = JSON.parse(obj)
}
const defn = new ProgramDefn()
if (obj && obj["P"] && Array.isArray(obj["P"])) {
const pages: any[] = obj["P"]
defn.pages = pages.map(pageDefnFromJson)
}
return defn
}
}