-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.ts
64 lines (62 loc) · 1.87 KB
/
convert.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
import { PSMapEntry, PSMapKey, PSValue } from "./types.ts";
/**
* Convert a JavaScript value into a PlatformScript value
*/
export function js2ps(value: unknown): PSValue {
let type = typeof value;
if (type === "number") {
return { type, value: value as number };
} else if (type === "boolean") {
return { type, value: value as boolean };
} else if (type === "string") {
return { type, value: value as string };
} else if (type === "object") {
if (Array.isArray(value)) {
return { type: "list", value: value.map(js2ps) };
} else {
if (typeof value === "undefined") {
throw new Error(
`'undefined' cannot be converted into a PlatformScript value`,
);
}
let record = value as Record<string, unknown>;
return {
type: "map",
value: new Map(
Object.keys(record).flatMap((key) => {
if (typeof key === "string") {
let pskey: PSMapKey = { type: "string", value: key };
let entry: PSMapEntry = [pskey, js2ps(record[key])];
return [entry];
} else {
return [];
}
}),
),
};
}
} else {
throw new Error(
`cannot convert JavaScript value: '${value}' into PlatformScript`,
);
}
}
/**
* Convert a PlatformScript value into a JavaScript value
*/
export function ps2js(value: PSValue): unknown {
switch (value.type) {
case "list":
return value.value.map(ps2js);
case "map":
return [...value.value.entries()].reduce((obj, [k, v]) => {
return Object.assign(obj, { [k.value.toString()]: ps2js(v) });
}, {});
case "fn":
throw new Error("TODO: convert PlatformScript fn into callable JS fn");
case "ref":
throw new Error("TODO: de-reference YS references when converting to JS");
default:
return value.value;
}
}