1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | const cache = new WeakMap();
|
8 |
|
9 | class ObjectStructure {
|
10 | constructor(keys) {
|
11 | this.keys = keys;
|
12 | this.children = new Map();
|
13 | }
|
14 |
|
15 | getKeys() {
|
16 | return this.keys;
|
17 | }
|
18 |
|
19 | key(key) {
|
20 | const child = this.children.get(key);
|
21 | if (child !== undefined) return child;
|
22 | const newChild = new ObjectStructure(this.keys.concat(key));
|
23 | this.children.set(key, newChild);
|
24 | return newChild;
|
25 | }
|
26 | }
|
27 |
|
28 | const getCachedKeys = (keys, cacheAssoc) => {
|
29 | let root = cache.get(cacheAssoc);
|
30 | if (root === undefined) {
|
31 | root = new ObjectStructure([]);
|
32 | cache.set(cacheAssoc, root);
|
33 | }
|
34 | let current = root;
|
35 | for (const key of keys) {
|
36 | current = current.key(key);
|
37 | }
|
38 | return current.getKeys();
|
39 | };
|
40 |
|
41 | class PlainObjectSerializer {
|
42 | serialize(obj, { write }) {
|
43 | const keys = Object.keys(obj);
|
44 | if (keys.length > 1) {
|
45 | write(getCachedKeys(keys, write));
|
46 | for (const key of keys) {
|
47 | write(obj[key]);
|
48 | }
|
49 | } else if (keys.length === 1) {
|
50 | const key = keys[0];
|
51 | write(key);
|
52 | write(obj[key]);
|
53 | } else {
|
54 | write(null);
|
55 | }
|
56 | }
|
57 | deserialize({ read }) {
|
58 | const keys = read();
|
59 | const obj = {};
|
60 | if (Array.isArray(keys)) {
|
61 | for (const key of keys) {
|
62 | obj[key] = read();
|
63 | }
|
64 | } else if (keys !== null) {
|
65 | obj[keys] = read();
|
66 | }
|
67 | return obj;
|
68 | }
|
69 | }
|
70 |
|
71 | module.exports = PlainObjectSerializer;
|