Last active
August 29, 2015 14:21
-
-
Save MNBuyskih/360a81fae851faa25c92 to your computer and use it in GitHub Desktop.
Underscore.js deepClone function. Src is https://github.com/jashkenas/underscore/issues/162#issuecomment-2391752
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 (obj, depth) { | |
var clone; | |
if (!obj || (typeof obj !== 'object')) { | |
clone = obj; // by value | |
} else if (_.isString(obj)) { | |
clone = String.prototype.slice.call(obj); | |
} else if (_.isDate(obj)) { | |
clone = new Date(obj.valueOf()); | |
} else if (_.isFunction(obj.clone)) { | |
clone = obj.clone(); | |
} else if (_.isArray(obj)) { | |
clone = Array.prototype.slice.call(obj); | |
} else if (obj.constructor !== {}.constructor) { | |
clone = obj; // by reference | |
} else { | |
clone = _.extend({}, obj); | |
} | |
if (!_.isUndefined(depth) && (depth > 0)) { | |
_.each(clone, function (element, key) { | |
clone[key] = deepClone(element, depth - 1); | |
}); | |
} | |
return clone; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed to be validated in JSLint