Created
June 18, 2021 16:28
-
-
Save rajatjain-21/02e2c5a30cf9d0190cb5503a25417fd1 to your computer and use it in GitHub Desktop.
This file contains 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