Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/deepCopy.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const v8 = require('v8'); // Node v11 and onwards

/**
* A function to deeply copy an object
* (circular references will break it).
* @param {(Object | Array)} o - The object or array you want to copy
* @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;
27 changes: 27 additions & 0 deletions src/tests/deepCopy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

});