Created
February 11, 2023 09:38
-
-
Save leihuang23/21944110f7627b984ee1e412bdfdf517 to your computer and use it in GitHub Desktop.
Detect cyclic object reference in JavaScript.
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
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