Deepclone

stdtraits~ Deepclone

Source:

Re­curs­ively clone an ob­ject.

const {Deep­clone, deep­clone} = re­quire('fer­rum');

class Bar {
  con­structor(foo, bang) {
    this.foo = foo;
    this.bang = bang;
  }

  [Deep­clone.sym]() {
    re­turn new Bar(deep­clone(this.foo), deep­clone(this.bar));
  }
}

const a = new Bar({foo: 42}, {bar: 5});
const b = deep­clone(a);

as­sert(a !== b);
as­ser­tEquals(a, b);

a.foo.foo = 5;
as­sert(b.foo.foo === 42);

In­ter­face

(x: The­Value) => r: The­Value

Laws

  • x !== r
  • x equals r wehre eq is the equals() func­tion.
  • get(r, k) !== get(x, k) for any k.
  • has(r, k) im­plies has(x, k) for any k.
  • get(r, k) equals get(x, k) for any k wehre eq is the equals() func­tion.
  • The above laws ap­ply re­curs­ively for any chil­dren.

Spe­cial­iz­a­tion Notes

No im­ple­ment­a­tion provided for set: In sets keys and val­ues are the same thing. If we cloned sets deeply, has(orig, key) im­plies has(clone, key) would be vi­ol­ated and the sets would not be equal after clon­ing. For the same reason, Map keys are not cloned either!

See: deep­clone