Last active
October 27, 2021 03:29
-
-
Save saitonakamura/d51aa672c929e35cc81fa5a0e31f12a9 to your computer and use it in GitHub Desktop.
Function that replace circular js object dependency with "[Circular]" so it can be consumed by 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
// DISCLAIMER | |
// Original function was updated to a faster and es5-supporting version by @Quacky2200 | |
var replaceCircular = function(val, cache) { | |
cache = cache || new WeakSet(); | |
if (val && typeof(val) == 'object') { | |
if (cache.has(val)) return '[Circular]'; | |
cache.add(val); | |
var obj = (Array.isArray(val) ? [] : {}); | |
for(var idx in val) { | |
obj[idx] = replaceCircular(val[idx], cache); | |
} | |
cache.delete(val); | |
return obj; | |
} | |
return val; | |
}; | |
// var a = { f: "asd", b: undefined } | |
// var b = { h: 123, a: a } | |
// a.b = b | |
// console.log(JSON.stringify(replaceCircular(a))) | |
// { "f": "asd", "b": { "h": 123, "a": "[Circular]" } } |
Wow, you people are great! @Quacky2200 I'll update the original to replaceCircular6
and mention you if you don't mind
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry to spam the comment section...
@jt0dd I noticed you're calling the original function replaceCircular in the replaceCircularFast function. When I change this to replaceCircularFast, this changes the result to ~50ms.
I also decided to run more tests with slight differences before actually realising the mistake above... I thought it was quite interesting. The array lamdba functions used in the original can still take over 100ms worst case. The iteration function from my last comment is still somewhat quite low in my results, yet it's actually higher than my original recursive refactor comment!
The iteration function forgets to create a new instance which causes the original argument object to change (whoops, my bad 😞 ). My original comment seems to give the lowest result, type equality (===) differences give a teeny-tiny neglible speed boost.
Test Code
Browser:
Node: