Search code examples
javascriptjsonhashcodecyclic-reference

JSON.stringify cyclic object n^2


I need to JSON.stringify a possibly cyclic object, which means that I have to pre-process the object and remove cycles. I'm already aware of the n^2 indexOf solution. Since that javascript doesn't seem to expose an object id or memory location, nor a generic hashcode for any object, is there a way to make the containment check faster?


Solution

  • An ES6 Set object can keep track of objects visited directly. As you're traversing through the object, you put each object into the Set and then a simple objSet.has(obj) will tell if you've already encountered this object of not.

    Work-arounds when that ES6 Set is not available usually involve adding a non-enumerable uniquely generated string key to each object so you can put that in a regular object map which is shown here in this ES6 Set polyfill.