Skip to content

Instantly share code, notes, and snippets.

@circAssimilate
Created March 9, 2021 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save circAssimilate/1674b349f6272f09e5392344d5f3ba05 to your computer and use it in GitHub Desktop.
Save circAssimilate/1674b349f6272f09e5392344d5f3ba05 to your computer and use it in GitHub Desktop.
/**
* @see https://stackoverflow.com/questions/14962018/detecting-and-fixing-circular-references-in-javascript
*/
export function isCyclic(obj: Record<string, unknown>): boolean {
const seenObjects: unknown[] = [];
function detect(objToDetect: unknown) {
if (objToDetect && typeof objToDetect === 'object') {
if (seenObjects.includes(objToDetect)) {
return true;
}
seenObjects.push(objToDetect);
for (const [key, value] of Object.entries(objToDetect ?? {})) {
if (
Object.prototype.hasOwnProperty.call(objToDetect, key) &&
detect(value)
) {
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