lukeed / klona

A tiny (240B to 501B) and fast utility to "deep clone" Objects, Arrays, Dates, RegExps, and more!
MIT License
1.61k stars 43 forks source link

Ignore circular references #37

Open muuvmuuv opened 2 years ago

muuvmuuv commented 2 years ago

I am trying to tidy our codebase and replace all of our _.deepClone stuff with Klona or with simpler solutions where it fits. Unfortunately, in one case where a deep clone is required, we have a circular ref that we cannot remove at this point. Would it be possible for Klona to ignore a circular ref or add some option how to handle these, so we could ignore it?

I expect something like

const circRef = {...}
const cloned = klona(circRef, {
  onCircularReference(ref) {
    return undefined
  }
})

I am also happy with any package that removes circular references, but I would love to have both in one place.

maxmilton commented 2 years ago

Seems out of scope since the project is solely focused on cloning... however I do see the appeal of avoiding additional looping if you're working with gigantic objects or need to do a huge number of clones.

For the time being, if your objects are JSON serializable you can use the replacer parameter of JSON.stringify. There's a good example on MDN. Otherwise I'd just loop with similar logic.

muuvmuuv commented 2 years ago

Unfortunately it is more complex since its the input of our apps logs and therefor it can be ANY valid JS object. I fiddled something together and will try it this week. Maybe it can be another file "circular" of you are interested. Anyway will post my changes as soon as I have something together.

muuvmuuv commented 2 years ago

Ok, I will post my PR soon, no need to accept it. I also made some other adjustments which besides the circular might be a good fit.