Last active
December 15, 2015 03:39
-
-
Save h2non/5195672 to your computer and use it in GitHub Desktop.
Simple function to create secure inmutable (recursive deep copy) JavaScript Objects
This file contains hidden or 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
/** | |
* Simple function to create secure inmutable (recursive deep copy) JavaScript Objects | |
* @license WTFPL | |
* @param {Object/Array} obj Target Object. Required | |
* @param {Number} depth Depth level. Defaults to 1 | |
* @return {Object/Array) Inmutable new Object | |
* @method deepClone | |
*/ | |
function deepClone(obj, depth) { | |
var clone, key, | |
toStr = Object.prototype.toString; | |
depth = depth || 1; | |
if (typeof obj !== 'object' || obj === null) { return obj; } | |
if (toStr.call(obj) === '[object String]') { return obj.splice(); } | |
if (toStr.call(obj) === '[object Date]') { return new Date(obj.getTime()); } | |
if (toStr.call(obj.clone) === '[object Function]') { return obj.clone(); } | |
clone = toStr.call(obj) === '[object Array]' ? obj.slice() : (function(obj){ | |
var k, o = {}; | |
for (k in obj) { o[k] = obj[k]; } | |
return o; | |
}(obj)); | |
if (depth !== undefined && depth > 0) { | |
for (key in clone) { | |
clone[key] = deepClone(clone[key], depth-1); | |
} | |
} | |
return clone; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment