hughsk / flat

:steam_locomotive: Flatten/unflatten nested Javascript objects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for cyclic objects

maximilianMairinger opened this issue · comments

Any thoughts on supporting cyclic objects?

Currently, this doesn't work.

let ob = {}
ob.a = ob
ob.key = {key2: 2}

flat(ob) // Uncaught RangeError: Maximum call stack size exceeded

Performance would probably take a hit... So, only under a flag? Or even better, under a separate function to keep it tree shakeable.

I think it would make sense to not only support it, but also make the effort to find the shortest path from the root.

My proposal would be to walk through the object level by level, write all non-cyclic references to the output object with concatenated keys. Also keep a reference in a weak map to every object that has been walked. When discovering a new object, before walking through it, check the set, and if found there simply ignore the key, as everything inside has already been discovered by a shorter path.

Keywords: cyclic, self-referencing, recursive, circular