1 var Flatted = (function (Primitive, primitive) {
6 * Copyright (c) 2018, Andrea Giammarchi, @WebReflection
8 * Permission to use, copy, modify, and/or distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
17 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18 * PERFORMANCE OF THIS SOFTWARE.
23 parse: function parse(text, reviver) {
24 var input = JSON.parse(text, Primitives).map(primitives);
26 var $ = reviver || noop;
27 var tmp = typeof value === 'object' && value ?
28 revive(input, new Set, value, $) :
30 return $.call({'': tmp}, '', tmp);
33 stringify: function stringify(value, replacer, space) {
39 $ = replacer && typeof replacer === typeof input ?
41 if (k === '' || -1 < replacer.indexOf(k)) return v;
44 i = +set(known, input, $.call({'': value}, '', value)),
45 replace = function (key, value) {
50 var after = $.call(this, key, value);
51 switch (typeof after) {
53 if (after === null) return after;
55 return known.get(after) || set(known, input, after);
62 output[i] = JSON.stringify(input[i], replace, space);
64 return '[' + output.join(',') + ']';
71 function noop(key, value) {
75 function revive(input, parsed, output, $) {
76 return Object.keys(output).reduce(
77 function (output, key) {
78 var value = output[key];
79 if (value instanceof Primitive) {
80 var tmp = input[value];
81 if (typeof tmp === 'object' && !parsed.has(tmp)) {
83 output[key] = $.call(output, key, revive(input, parsed, tmp, $));
85 output[key] = $.call(output, key, tmp);
88 output[key] = $.call(output, key, value);
95 function set(known, input, value) {
96 var index = Primitive(input.push(value) - 1);
97 known.set(value, index);
101 // the two kinds of primitives
103 // 2. the wrapped one
105 function primitives(value) {
106 return value instanceof Primitive ? Primitive(value) : value;
109 function Primitives(key, value) {
110 return typeof value === primitive ? new Primitive(value) : value;
113 }(String, 'string'));
114 export default Flatted;
115 export var parse = Flatted.parse;
116 export var stringify = Flatted.stringify;