diff --git a/src/deepCopy.js b/src/deepCopy.js index 4fa8cb5..33f6a83 100644 --- a/src/deepCopy.js +++ b/src/deepCopy.js @@ -1,3 +1,5 @@ +const v8 = require('v8'); // Node v11 and onwards + /** * A function to deeply copy an object * (circular references will break it). @@ -5,7 +7,7 @@ * @return {(Object | Array)} - The new, cloned object or array */ const deepCopy = (o) => { - return JSON.parse(JSON.stringify(o)); + return v8.deserialize(v8.serialize(o)); }; module.exports = deepCopy; diff --git a/src/tests/deepCopy.test.js b/src/tests/deepCopy.test.js index 74f923a..7ac35c3 100644 --- a/src/tests/deepCopy.test.js +++ b/src/tests/deepCopy.test.js @@ -18,4 +18,31 @@ describe("deepCopy", () => { expect(newObj.name.first).to.equal("Alpha"); expect(myObj.name.first).to.equal("Bravo"); }); + it("can copy an object that has arrays as values", () => { + const myObj = { + a: [1], + } + const newObj = deepCopy(myObj); + expect(newObj.a).to.deep.equal(myObj.a); + }); + it("can copy an object that has undefined, NaN, Infinity as values", () => { + const myObj = { + a: [1], + b: new Date(), + c: undefined, + d: Infinity, + e: NaN, + f: false, + } + const newObj = deepCopy(myObj); + expect(newObj.a).to.deep.equal(myObj.a); + expect(newObj.b).to.deep.equal(myObj.b); + expect(newObj.c).to.equal(myObj.c); + expect(newObj.d).to.equal(myObj.d); + expect(newObj.e).to.not.equal(newObj.e); // test for NaN being copied over + // > NaN !== NaN + //true + expect(newObj.f).to.equal(myObj.f); + }); + });