1 | 'use strict'
|
2 |
|
3 | const {proxyHandler} = require('./proxyHandler');
|
4 | const proxyToObjMap = new WeakMap();
|
5 | const unwrappedDeep = new WeakMap();
|
6 |
|
7 | function wrap(val) {
|
8 | if (proxyToObjMap.has(val)) {
|
9 | return val;
|
10 | }
|
11 | const res = new Proxy(val, proxyHandler);
|
12 | proxyToObjMap.set(res, val);
|
13 | return res;
|
14 | }
|
15 |
|
16 | function unwrap(proxy) {
|
17 | let res = proxy;
|
18 | while (proxyToObjMap.has(proxy)) {
|
19 | res = proxyToObjMap.get(proxy);
|
20 | proxy = res;
|
21 | }
|
22 | if (Array.isArray(res)) {
|
23 | if (!unwrappedDeep.has(res)) {
|
24 | unwrappedDeep.set(res, true);
|
25 | res.forEach((val, key) => {
|
26 | res[key] = unwrap(val);
|
27 | });
|
28 | }
|
29 | } else if (typeof res === 'object' && res !== null) {
|
30 | if (!unwrappedDeep.has(res)) {
|
31 | unwrappedDeep.set(res, true);
|
32 | Object.getOwnPropertyNames(res).forEach(key => {
|
33 | res[key] = unwrap(res[key]);
|
34 | });
|
35 | }
|
36 | }
|
37 | return res;
|
38 | }
|
39 |
|
40 | module.exports = {
|
41 | unwrap,
|
42 | wrap
|
43 | };
|