1 /*! (c) 2020 Andrea Giammarchi */
3 const {parse: $parse, stringify: $stringify} = JSON;
6 const Primitive = String; // it could be Number
7 const primitive = 'string'; // it could be 'number'
10 const object = 'object';
12 const noop = (_, value) => value;
14 const primitives = value => (
15 value instanceof Primitive ? Primitive(value) : value
18 const Primitives = (_, value) => (
19 typeof value === primitive ? new Primitive(value) : value
22 const revive = (input, parsed, output, $) => {
24 for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) {
26 const value = output[k];
27 if (value instanceof Primitive) {
28 const tmp = input[value];
29 if (typeof tmp === object && !parsed.has(tmp)) {
32 lazy.push({k, a: [input, parsed, tmp, $]});
35 output[k] = $.call(output, k, tmp);
37 else if (output[k] !== ignore)
38 output[k] = $.call(output, k, value);
40 for (let {length} = lazy, i = 0; i < length; i++) {
41 const {k, a} = lazy[i];
42 output[k] = $.call(output, k, revive.apply(null, a));
47 const set = (known, input, value) => {
48 const index = Primitive(input.push(value) - 1);
49 known.set(value, index);
53 export const parse = (text, reviver) => {
54 const input = $parse(text, Primitives).map(primitives);
55 const value = input[0];
56 const $ = reviver || noop;
57 const tmp = typeof value === object && value ?
58 revive(input, new Set, value, $) :
60 return $.call({'': tmp}, '', tmp);
63 export const stringify = (value, replacer, space) => {
64 const $ = replacer && typeof replacer === object ?
65 (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
67 const known = new Map;
70 let i = +set(known, input, $.call({'': value}, '', value));
72 while (i < input.length) {
74 output[i] = $stringify(input[i++], replace, space);
76 return '[' + output.join(',') + ']';
77 function replace(key, value) {
82 const after = $.call(this, key, value);
83 switch (typeof after) {
85 if (after === null) return after;
87 return known.get(after) || set(known, input, after);
93 export const toJSON = any => $parse(stringify(any));
94 export const fromJSON = any => parse($stringify(any));