Skip to content

Instantly share code, notes, and snippets.

@ugochukwu95
Created January 15, 2020 16:30
Show Gist options
  • Save ugochukwu95/87513cce427b4e3926c5f6344f19e6d0 to your computer and use it in GitHub Desktop.
Save ugochukwu95/87513cce427b4e3926c5f6344f19e6d0 to your computer and use it in GitHub Desktop.
A function called DeepClone.js which takes an object and creates a copy of it. Tested using jest (see DeepClone.test.js)
const DeepClone = (obj) => {
let copy;
// Handle the 3 simple types, and null or undefined
if (null === obj || "object" !== typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
// A way to make one Date the same as another is by calling the setTime method
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (let i = 0; i < obj.length; ++i) {
copy[i] = DeepClone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (let attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = DeepClone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
module.exports = {DeepClone};
/**
* Used to test DeepClone.js
*/
const { DeepClone } = require('./DeepClone')
const obj = {name: "Paddy", address: {town: "Lerum", country: "Sweden"}};
test("cloning an object", () => {
// toEqual compares the values of two objects.
// it checks the equality of all the properties or elements.
// It does not compare references
expect(DeepClone(obj)).toEqual(obj)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment