-1

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?

ealfonso
  • 6,622
  • 5
  • 39
  • 67
  • 4
    possible duplicate of [Serializing object that contains cyclic object value](http://stackoverflow.com/questions/9382167/serializing-object-that-contains-cyclic-object-value) – fixmycode Sep 06 '15 at 22:31
  • An ES6 `Set` object can keep track of objects visited directly. Work-arounds when that 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 polyfill: https://github.com/jfriend00/ES6-Set/blob/master/set.js – jfriend00 Sep 06 '15 at 22:32
  • @jfriend00 thanks, that's probably what I was looking for. do you mind making that an answer? – ealfonso Sep 06 '15 at 22:49

1 Answers1

1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979