Open EdwardZZZ opened 4 years ago
const obj = {
a: 1,
b: 2,
c: 3,
d: new Map([
['a', 1],
['b', 2]
]),
e: new Set(['a', 'b', 'c', 'd']),
}
const type = (obj) => Object.prototype.toString.call(obj).slice(8, -1);
const format = () => {
const set = new WeakSet();
return (key, value) => {
if (set.has(value)) {
retrun `Circle *${key}`;
}
if (typeof value === 'object') set.add(value);
if (type(value) === 'Map') {
const mapObj = {};
for (const [k, v] of value) {
if (typeof k === 'object') {
console.log(`Cann't stringify Map's 'Object' key.`);
continue;
}
mapObj[k] = v;
}
// return `Map => ${JSON.stringify(mapObj)}`;
return {'Map =>': mapObj};
}
if (type(value) === 'Set') {
// return `Set => ${JSON.stringify([...value])}`;
return {'Set =>': [...value]};
}
return value;
}
}
const stringify = JSON.stringify;
JSON.stringify = (obj, replacer = format(), space = 4) => {
return stringify.call(JSON, obj, replacer, space);
}
console.log(JSON.stringify(obj));