Created
December 18, 2018 10:15
-
-
Save yiyizym/a9ecc7f1658f385a4abe40f08f65c25d to your computer and use it in GitHub Desktop.
deepclone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepClone(item) { | |
if (!item) { return item; } // null, undefined values check | |
var types = [ Number, String, Boolean ], | |
result; | |
// normalizing primitives if someone did new String('aaa'), or new Number('444'); | |
types.forEach(function(type) { | |
if (item instanceof type) { | |
result = type( item ); | |
} | |
}); | |
if (typeof result == "undefined") { | |
if (Object.prototype.toString.call( item ) === "[object Array]") { | |
result = []; | |
item.forEach(function(child, index, array) { | |
result[index] = deepClone( child ); | |
}); | |
} else if (typeof item == "object") { | |
// testing that this is DOM | |
if (item.nodeType && typeof item.cloneNode == "function") { | |
result = item.cloneNode( true ); | |
} else if (!item.prototype) { // check that this is a literal | |
if (item instanceof Date) { | |
result = new Date(item); | |
} else { | |
// it is an object literal | |
result = {}; | |
for (var i in item) { | |
result[i] = deepClone( item[i] ); | |
} | |
} | |
} else { | |
// depending what you would like here, | |
// just keep the reference, or create new object | |
if (false && item.constructor) { | |
// would not advice to do that, reason? Read below | |
result = new item.constructor(); | |
} else { | |
result = item; | |
} | |
} | |
} else { | |
result = item; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment