Deepclone

stdtraits~ Deepclone

Source:

Re­curs­ively clone an ob­ject.

const { stric­tEqual: as­sertIs, not­Stric­tEqual: as­sertIs­Not } = re­quire('assert');
const { Deep­clone, deep­clone, Equals, eq, as­ser­tEquals } = 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.bang));
  }

  [Equals.sym](otr) {
    re­turn eq(this.foo, otr.foo) && eq(this.bar, otr.bar);
  }
}

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

as­sertIs­Not(a, b);
as­ser­tEquals(a, b);

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

In­ter­face

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

Laws

  • x !== r
  • x equals r where 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 where 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