Skip to content

Instantly share code, notes, and snippets.

@yeonwooz
Created March 4, 2022 02:51
Show Gist options
  • Save yeonwooz/c8834d77c37f571025b3a45bfb8f6135 to your computer and use it in GitHub Desktop.
Save yeonwooz/c8834d77c37f571025b3a45bfb8f6135 to your computer and use it in GitHub Desktop.
deep copy (clone)
function clone(objectToBeCloned) {
// Basis.
if (!(objectToBeCloned instanceof Object)) {
return objectToBeCloned;
}
var objectClone;
// Filter out special objects.
var Constructor = objectToBeCloned.constructor;
switch (Constructor) {
// Implement other special objects here.
case RegExp:
objectClone = new Constructor(objectToBeCloned);
break;
case Date:
objectClone = new Constructor(objectToBeCloned.getTime());
break;
default:
objectClone = new Constructor();
}
// Clone each property.
for (var prop in objectToBeCloned) {
objectClone[prop] = clone(objectToBeCloned[prop]);
}
return objectClone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment