1 | import {
|
---|
2 | VOID, PRIMITIVE,
|
---|
3 | ARRAY, OBJECT,
|
---|
4 | DATE, REGEXP, MAP, SET,
|
---|
5 | ERROR, BIGINT
|
---|
6 | } from './types.js';
|
---|
7 |
|
---|
8 | const env = typeof self === 'object' ? self : globalThis;
|
---|
9 |
|
---|
10 | const deserializer = ($, _) => {
|
---|
11 | const as = (out, index) => {
|
---|
12 | $.set(index, out);
|
---|
13 | return out;
|
---|
14 | };
|
---|
15 |
|
---|
16 | const unpair = index => {
|
---|
17 | if ($.has(index))
|
---|
18 | return $.get(index);
|
---|
19 |
|
---|
20 | const [type, value] = _[index];
|
---|
21 | switch (type) {
|
---|
22 | case PRIMITIVE:
|
---|
23 | case VOID:
|
---|
24 | return as(value, index);
|
---|
25 | case ARRAY: {
|
---|
26 | const arr = as([], index);
|
---|
27 | for (const index of value)
|
---|
28 | arr.push(unpair(index));
|
---|
29 | return arr;
|
---|
30 | }
|
---|
31 | case OBJECT: {
|
---|
32 | const object = as({}, index);
|
---|
33 | for (const [key, index] of value)
|
---|
34 | object[unpair(key)] = unpair(index);
|
---|
35 | return object;
|
---|
36 | }
|
---|
37 | case DATE:
|
---|
38 | return as(new Date(value), index);
|
---|
39 | case REGEXP: {
|
---|
40 | const {source, flags} = value;
|
---|
41 | return as(new RegExp(source, flags), index);
|
---|
42 | }
|
---|
43 | case MAP: {
|
---|
44 | const map = as(new Map, index);
|
---|
45 | for (const [key, index] of value)
|
---|
46 | map.set(unpair(key), unpair(index));
|
---|
47 | return map;
|
---|
48 | }
|
---|
49 | case SET: {
|
---|
50 | const set = as(new Set, index);
|
---|
51 | for (const index of value)
|
---|
52 | set.add(unpair(index));
|
---|
53 | return set;
|
---|
54 | }
|
---|
55 | case ERROR: {
|
---|
56 | const {name, message} = value;
|
---|
57 | return as(new env[name](message), index);
|
---|
58 | }
|
---|
59 | case BIGINT:
|
---|
60 | return as(BigInt(value), index);
|
---|
61 | case 'BigInt':
|
---|
62 | return as(Object(BigInt(value)), index);
|
---|
63 | }
|
---|
64 | return as(new env[type](value), index);
|
---|
65 | };
|
---|
66 |
|
---|
67 | return unpair;
|
---|
68 | };
|
---|
69 |
|
---|
70 | /**
|
---|
71 | * @typedef {Array<string,any>} Record a type representation
|
---|
72 | */
|
---|
73 |
|
---|
74 | /**
|
---|
75 | * Returns a deserialized value from a serialized array of Records.
|
---|
76 | * @param {Record[]} serialized a previously serialized value.
|
---|
77 | * @returns {any}
|
---|
78 | */
|
---|
79 | export const deserialize = serialized => deserializer(new Map, serialized)(0);
|
---|