Skip to content

Instantly share code, notes, and snippets.

@lukas-zech-software
Last active July 9, 2019 11:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lukas-zech-software/fab77f7eb216d38f027ad8fd5347b1cb to your computer and use it in GitHub Desktop.
Save lukas-zech-software/fab77f7eb216d38f027ad8fd5347b1cb to your computer and use it in GitHub Desktop.
Detect circular references in objects
// http://blog.vjeux.com/2011/javascript/cyclic-object-detection.html.
function isCyclic (obj) {
var seenObjects = [];
function detect (obj) {
if (obj && typeof obj === 'object') {
if (seenObjects.indexOf(obj) !== -1) {
return true;
}
seenObjects.push(obj);
for (var key in obj) {
if (obj.hasOwnProperty(key) && detect(obj[key])) {
console.log(obj, 'cycle at ' + key);
return true;
}
}
}
return false;
}
return detect(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment