Created
January 30, 2015 23:30
-
-
Save zachwolf/81f0743e7b2aeb25a4f6 to your computer and use it in GitHub Desktop.
Deep clone function
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
/** | |
* 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