Skip to content

Instantly share code, notes, and snippets.

@h2non
Last active December 15, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2non/5195672 to your computer and use it in GitHub Desktop.
Save h2non/5195672 to your computer and use it in GitHub Desktop.
Simple function to create secure inmutable (recursive deep copy) JavaScript Objects
/**
* 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