Skip to content

Instantly share code, notes, and snippets.

@MNBuyskih
Last active August 29, 2015 14:21
Show Gist options
  • Save MNBuyskih/360a81fae851faa25c92 to your computer and use it in GitHub Desktop.
Save MNBuyskih/360a81fae851faa25c92 to your computer and use it in GitHub Desktop.
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;
};
@MNBuyskih
Copy link
Author

Fixed to be validated in JSLint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment