Last active
January 31, 2020 17:32
-
-
Save celwell/47a01af2ce66a281d23a5090f23724a5 to your computer and use it in GitHub Desktop.
Recursive re-implementation of JSON.stringify
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
function stringify(obj, seenStack = []) { | |
if (obj instanceof Array) { | |
return "[" + | |
obj.reduce((acc, v, idx) => { | |
let sanitizedV = v; | |
if (typeof sanitizedV === 'string') { | |
sanitizedV = "\"" + sanitizedV + "\""; | |
} | |
return acc + (idx !== 0 ? "," : "") + stringify(sanitizedV, seenStack); | |
}, "") + | |
"]"; | |
} else if (typeof obj === 'object' && obj !== null) { | |
return "{" + | |
Object.entries(obj).reduce((acc, [k, v], idx) => { | |
if (typeof v !== 'undefined') { | |
if (seenStack.indexOf(v) !== -1) { | |
return acc + '[circular reference]'; | |
} | |
return acc + | |
(idx !== 0 ? "," : "") + | |
"\"" + k + "\":" + | |
stringify(v, (seenStack.push(v) && seenStack)); | |
} else { | |
return acc; | |
} | |
}, "") + | |
"}"; | |
} else if (typeof obj !== 'undefined') { | |
return "" + obj; | |
} else { | |
return ""; | |
} | |
} | |
const test1 = {"a": 5, "b": null, "c": undefined}; | |
console.log(stringify(test1), 'should be', JSON.stringify(test1)); | |
const test2 = {"a": 5, | |
"b": {"d": 23, | |
"e": 24}, | |
"c": 99}; | |
console.log(stringify(test2), 'should be', JSON.stringify(test2)); | |
const test3 = 8; | |
console.log(stringify(test3), 'should be', JSON.stringify(test3)); | |
const test4 = {}; | |
const test5 = {"b": test4, | |
"c": 8, | |
"d": {"e": 9, | |
"f": {"g": 10}}}; | |
test4.a = test5; | |
console.log(stringify(test4)); | |
/* JSON.stringify will throw error here (at least if running in jsbin.com) | |
console.log('should be', JSON.stringify(test4)); | |
*/ | |
const test6 = ['a', 'b', 8, test2]; | |
console.log(stringify(test6), 'should be', JSON.stringify(test6)); | |
// possible improvements: | |
// dates differently? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment