UNPKG

1.87 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
5 * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
6 * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
7 *
8 * Includes extensions for handling Map and Set objects.
9 */
10function applyReviver(reviver, obj, key, val) {
11 if (val && typeof val === 'object') {
12 if (Array.isArray(val)) {
13 for (let i = 0, len = val.length; i < len; ++i) {
14 const v0 = val[i];
15 const v1 = applyReviver(reviver, val, String(i), v0);
16 if (v1 === undefined)
17 delete val[i];
18 else if (v1 !== v0)
19 val[i] = v1;
20 }
21 }
22 else if (val instanceof Map) {
23 for (const k of Array.from(val.keys())) {
24 const v0 = val.get(k);
25 const v1 = applyReviver(reviver, val, k, v0);
26 if (v1 === undefined)
27 val.delete(k);
28 else if (v1 !== v0)
29 val.set(k, v1);
30 }
31 }
32 else if (val instanceof Set) {
33 for (const v0 of Array.from(val)) {
34 const v1 = applyReviver(reviver, val, v0, v0);
35 if (v1 === undefined)
36 val.delete(v0);
37 else if (v1 !== v0) {
38 val.delete(v0);
39 val.add(v1);
40 }
41 }
42 }
43 else {
44 for (const [k, v0] of Object.entries(val)) {
45 const v1 = applyReviver(reviver, val, k, v0);
46 if (v1 === undefined)
47 delete val[k];
48 else if (v1 !== v0)
49 val[k] = v1;
50 }
51 }
52 }
53 return reviver.call(obj, key, val);
54}
55
56exports.applyReviver = applyReviver;