-
-
Save thamsrang/2b5ee02aef5711ac6a724371b066f8dd 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
// This implementation does not work with Symbols, BigInts | |
function stringify(data) { | |
if (data === undefined) | |
return undefined | |
if (data === null) | |
return 'null' | |
if (data.toString() === "NaN") | |
return 'null' | |
if (data === Infinity) | |
return 'null' | |
if (data.constructor === String) | |
return '"' + data.replace(/"/g, '\\"') + '"' | |
if (data.constructor === Number) | |
return String(data) | |
if (data.constructor === Boolean) | |
return data ? 'true' : 'false' | |
if (data.constructor === Array) | |
return '[' + data.reduce((acc, v) => { | |
if (v === undefined || v === NaN || v === Infinity) | |
return [...acc, 'null'] | |
else | |
return [...acc, stringify(v)] | |
}, []).join(',') + ']' | |
if (data.constructor === Object) | |
return '{' + Object.keys(data).reduce((acc, k) => { | |
if (data[k] === undefined) | |
return acc | |
else | |
return [...acc, stringify(k) + ':' + stringify(data[k])] | |
}, []).join(',') + '}' | |
return '{}' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment