Created
November 23, 2015 11:59
-
-
Save ssnau/3a3bf49ff47d81da1df4 to your computer and use it in GitHub Desktop.
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 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