Created
October 24, 2015 20:15
-
-
Save cmstead/59675cb818593b197839 to your computer and use it in GitHub Desktop.
Clone method from JFP 2.4.0
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 clone (originalValue, depth) { | |
var depthOkay = j.isUndefined(depth) || j.geq(depth, 0), | |
copyOkay = j.isType('object', originalValue) || j.isType('array', originalValue); | |
function copy () { | |
var keys = Object.keys(originalValue), | |
container = j.isArray(originalValue) ? [] : {}; | |
j.each(function (key) { | |
var newDepth = j.isNumber(depth) ? depth - 1 : undefined; | |
try { | |
container[key] = clone(originalValue[key], newDepth); | |
} catch (err) { | |
throw new RangeError('Object contains circular reference or is too deep to clone.'); | |
} | |
}, keys); | |
return container; | |
} | |
return copyOkay && depthOkay ? copy() : originalValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment