Function objDeepCopy

  • Performs a deep copy of the source object, this is designed to work with base (plain) objects, arrays and primitives if the source object contains class objects they will either be not cloned or may be considered non-operational after performing a deep copy. ie. This is performing a deep copy of the objects properties so that altering the copy will not mutate the source object hierarchy. Automatic handling of recursive properties was added in v0.4.4.

    Type Parameters

    • T

    Parameters

    • source: T

      The source object to be copied

    • Optionalhandler: ObjDeepCopyHandler

      An optional callback that lets you provide / overide the deep cloning (Since 0.4.4)

    Returns T

    A new object which contains a deep copy of the source properties

    let a: any = { a: 1 };
    let b: any = { b: 2, d: new Date(), e: new TestClass("Hello Darkness") };
    a.b = b; // { a: 1, b: { b: 2} }
    b.a = a; // { a: 1, b: { b: 2, a: { a: 1, { b: 2, a: ... }}}}

    function copyHandler(details: IObjDeepCopyHandlerDetails) {
    // details.origin === a
    // details.path[] is the path to the current value
    if (details.value && isDate(details.value)) {
    // So for the date path === [ "b", "d" ] which represents
    // details.origin["b"]["d"] === The Date

    // Return true to indicate that we have "handled" the conversion
    // Which in this case will reuse the existing instance (as we didn't replace details.value)
    // See objCopyProps example for replacing the Date instance
    return true;
    }

    return false;
    }

    let c: any = objDeepCopy(a, copyHandler);

    assert.notEqual(a, c, "check a and c are not the same");
    assert.ok(c === c.b.a, "The root object won't be the same for the target reference");
    assert.ok(c.b === c.b.a.b, "Check that the 2 'b' references are the same object");
    assert.ok(c.b.a === c.b.a.b.a, "Check that the 2 'a' references are the same object");
    assert.ok(c.b.d === c.b.a.b.d, "Check that the 2 'd' references are the same object");
    assert.ok(isDate(c.b.d), "The copied date is still real 'Date' instance");
    assert.equal(c.b.d, a.b.d, "And the copied date is the original date");
    assert.equal(c.b.d.getTime(), a.b.d.getTime(), "But the dates are the same");
    assert.ok(isObject(c.b.d), "The copied date is now an object");
    assert.ok(!isError(c.b.e), "The copied error is no longer a real 'Error' instance");
    assert.ok(isObject(c.b.e), "The copied error is now an object");
    assert.equal(42, c.b.e.value, "Expect that the local property was copied");