Skip to content

Instantly share code, notes, and snippets.

@zachwolf
Created January 30, 2015 23:30
Show Gist options
  • Save zachwolf/81f0743e7b2aeb25a4f6 to your computer and use it in GitHub Desktop.
Save zachwolf/81f0743e7b2aeb25a4f6 to your computer and use it in GitHub Desktop.
Deep clone function
/**
* Creates a copy of a mutable object to a certain depth.
* Useful when nested obects need to be cloned, since _.clone only
* produces a shallow copy.
*
* NOTE: this function is overkill if you want to copy the whole thing without a depth limit.
* Alternatively, just stringify and parse the object like:
function deepClone (obj) {
return JSON.parse(JSON.stringify(obj));
}
*
* @param {object|array} obj - thing to be copied
* @param {number|undefined} depth - levels to copy
* @returns {object}
*/
var deepClone = (function(){
'use strict';
/**
* Checks if a value is an object or array
*
* @param {object|array} val - value to check
* @returns {boolean}
*/
function _isMutable (val) {
return _.isArray(val) || _.isObject(val);
}
/**
* Returns empty type of thing passed
*
* @param {object|array} val
* @returns {object|array}
*/
function _dupType (val) {
return _.isArray(val) ? [] : {};
}
/**
* Recursively loops through data and copies it
*
* @param {object|array} dest - thing to populate with
* @param {object|array} src - thing to copy
* @param {number} depth - depth to loop through and copy
* @param {number} curDepth - internally track how far the element has been looped through
* @returns {object|array}
*/
function _deepClone (dest, src, depth, curDepth) {
console.log(src, depth, !_.isNull(depth), curDepth, depth)
if (!_.isNull(depth) && curDepth > depth) {
return src;
}
_.map(src, function (val, key) {
if (_isMutable(val)) {
dest[key] = _deepClone(_dupType(val), val, depth, curDepth + 1);
} else {
dest[key] = val;
}
})[0];
return dest;
}
return function (obj, depth) {
return _deepClone(_dupType(obj), obj, _.isUndefined(depth) ? null : depth, 0);
}
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment