Created
October 21, 2019 12:40
-
-
Save lac5/b2604d8b12d6c275fdac6c272995aa6c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let seen = new WeakMap(); | |
function safeJson(key, value) { | |
if (key.startsWith('_') || key.startsWith('$')) return; | |
if (typeof value === 'function') return; | |
if (typeof value === 'bigint' || typeof value === 'symbol') { | |
return String(value); | |
} | |
if (typeof value === 'object') { | |
if (value instanceof Date) { | |
return value.toISOString(); | |
} | |
if (value instanceof RegExp) { | |
return value.toString(); | |
} | |
let newValue = seen.get(value); | |
if (value instanceof Set) { | |
if (!Array.isArray(newValue)) { | |
newValue = Array.from(value); | |
newValue.$class = 'Set'; | |
seen.set(value, newValue); | |
} else { | |
newValue.length = value.size; | |
let i = 0; | |
for (let x of value) { | |
newValue[i] = x; | |
i++; | |
} | |
} | |
return newValue; | |
} | |
if (value instanceof Map) { | |
if (Object.prototype.toString.call(newValue) !== '[object Object]') { | |
newValue = {}; | |
newValue.$class = 'Map'; | |
seen.set(value, newValue); | |
} else { | |
for (let k in newValue) { | |
if (!value.has(k)) { | |
delete newValue[k]; | |
} | |
} | |
} | |
for (let [k, v] of value) { | |
newValue[k] = v; | |
} | |
return newValue; | |
} | |
} | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment