Created
August 18, 2023 07:30
-
-
Save FlameWolf/2a6c889bad3d37656a6e9bfb28bf9034 to your computer and use it in GitHub Desktop.
Get `Object.prototype.toString()` to return JSON string without circular reference error
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
Object.defineProperty(Object.prototype, "toString", { | |
value: function () { | |
return JSON.stringify( | |
this, | |
(function () { | |
const ancestors = []; | |
return function (key, value) { | |
if (typeof value !== "object" || value === null) { | |
return value; | |
} | |
while (ancestors.length > 0 && ancestors.at(-1) !== this) { | |
ancestors.pop(); | |
} | |
if (ancestors.includes(value)) { | |
return "[Circular]"; | |
} | |
ancestors.push(value); | |
return value; | |
}; | |
})() | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment