Created
February 6, 2023 11:28
-
-
Save mrgrain/a61408a4e8dd2006be5000a6523bf28e to your computer and use it in GitHub Desktop.
stringify javascript values with support for Symbols that will be rendered as is
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
function stringify(data, indentation = 2) { | |
if (typeof indentation === "number") { | |
return doStringify(data, 0, " ".repeat(indentation)) | |
} | |
return doStringify(data, 0, indentation) | |
} | |
function doStringify(data, level = 0, idt = " ") { | |
if (typeof data === "symbol") { | |
return data.description; | |
} | |
if (Array.isArray(data)) { | |
return "[" + "\n" | |
+ data.map(val => idt.repeat(level + 1) + doStringify(val, level + 1, idt) + ",").join('\n') | |
+ "\n" + idt.repeat(level) + "]" | |
} | |
if (data && typeof data === 'object') { | |
return "{" + "\n" | |
+ Object.entries(data) | |
.map(([key, val]) => idt.repeat(level + 1) + JSON.stringify(key) + ": " + doStringify(val, level + 1, idt) + ",") | |
.join("\n") | |
+ "\n" + idt.repeat(level) + "}" | |
} | |
return JSON.stringify(data); | |
} | |
console.log(stringify([1, "string", true, { | |
a: "b" | |
}])) | |
console.log(stringify({ | |
"null": null, | |
"infinity": Infinity, | |
"date": Date.now(), | |
banana: "bread", | |
"foo": "bar", | |
"number": 1, | |
"truth": false, | |
"array": [1, "string", true, { | |
a: "b" | |
}], | |
"object": { | |
"a": "b", | |
sym: Symbol("__dirname"), | |
func: Symbol("JSON.stringify(1)") | |
} | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output