-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.js
34 lines (30 loc) · 844 Bytes
/
types.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
var typeRegistry = new Map();
class Types {
static register(name, type) {
type.prototype[Symbol.toStringTag] = name;
typeRegistry.set(name, type);
}
static create(name) {
if (!typeRegistry.has(name))
throw new Error(`Bad type: ${name}`);
return typeRegistry.get(name).create();
}
static fromJSON(json) {
if (!(json instanceof Array))
throw new Error("Bad types");
return json.map((item) => {
if (!typeRegistry.has(item[0]))
throw new Error(`Unknown type: ${item[0]}`);
var cons = typeRegistry.get(item[0]);
return new cons(...item.slice(1));
});
}
static toJSON(types) {
return types.map((t) => {
for (var e of typeRegistry.entries()) {
if (t instanceof e[1]) return [e[0]].concat(t.toJSON());
}
throw new Error(`Bad type: ${t.toString()}`);
});
}
};