Skip to content

Instantly share code, notes, and snippets.

@uttarwarsandesh33
Last active September 12, 2021 14:47
Show Gist options
  • Save uttarwarsandesh33/028dcd7383b101860e7e561af17aac81 to your computer and use it in GitHub Desktop.
Save uttarwarsandesh33/028dcd7383b101860e7e561af17aac81 to your computer and use it in GitHub Desktop.
Create deep copy with recursive method
//recursive method to create deep copy
function deepCopy(obj) {
if (null === obj || 'object' !== typeof obj) return obj;
switch (obj.constructor) {
case Boolean:
return new Boolean(obj);
case Number:
return new Number(obj);
case String:
return new String(obj);
case Date:
return new Date().setTime(obj.getTime());
case Array:
return obj.map((o) => deepCopy1(o));
case RegExp:
return new RegExp(obj);
case BigInt:
return BigInt(obj);
case Object: {
let copy = {};
Object.keys(obj).forEach((key) => {
if (obj.hasOwnProperty(key)) copy[key] = deepCopy1(obj[key]);
});
return copy;
}
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment