Skip to content

Instantly share code, notes, and snippets.

@ssnau
Created November 23, 2015 11:59
Show Gist options
  • Save ssnau/3a3bf49ff47d81da1df4 to your computer and use it in GitHub Desktop.
Save ssnau/3a3bf49ff47d81da1df4 to your computer and use it in GitHub Desktop.
function isObject(obj) {
return !!obj && typeof obj === 'object';
}
function find(arr, key, target) {
var len = arr.length;
for (var i = 0; i < len; i++) {
if (!arr[i]) continue;
if (arr[i][key] === target) return arr[i];
}
}
function deepClone(object) {
var objects = [];
var count = 0;
function _deepClone(obj) {
count++;
if (count > 100) {
throw new Error('probably too deep to clone..')
}
var res = {};
objects.push({
source: obj,
dest: res
});
Object.keys(obj).forEach(function(k) {
if (isObject(obj[k])) {
var j = find(objects, 'source', obj[k]);
if (j) { res[k] = j.dest; return; }
res[k] = _deepClone(obj[k]);
} else {
res[k] = obj[k];
}
});
return res;
}
return _deepClone(object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment