Skip to content

Instantly share code, notes, and snippets.

@cmstead
Created October 24, 2015 20:15
Show Gist options
  • Save cmstead/59675cb818593b197839 to your computer and use it in GitHub Desktop.
Save cmstead/59675cb818593b197839 to your computer and use it in GitHub Desktop.
Clone method from JFP 2.4.0
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