Skip to content

Instantly share code, notes, and snippets.

@leihuang23
Created February 11, 2023 09:38
Show Gist options
  • Save leihuang23/21944110f7627b984ee1e412bdfdf517 to your computer and use it in GitHub Desktop.
Save leihuang23/21944110f7627b984ee1e412bdfdf517 to your computer and use it in GitHub Desktop.
Detect cyclic object reference in JavaScript.
export default function isCyclic(object, seen = new WeakSet().add(object)) {
const props = getProps(object)
let len = props.length
while (len--) {
const value = object[props[len]]
if (value instanceof Object) {
if (seen.has(value)) {
return true
}
return isCyclic(value, seen.add(value))
}
}
return false
}
function getProps(object) {
const props = Object.keys(object)
if (Object.getOwnPropertySymbols) {
const symbolProperties = Object.getOwnPropertySymbols(object)
Array.prototype.push.apply(props, symbolProperties)
}
return props
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment