Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Created August 18, 2023 07:30
Show Gist options
  • Save FlameWolf/2a6c889bad3d37656a6e9bfb28bf9034 to your computer and use it in GitHub Desktop.
Save FlameWolf/2a6c889bad3d37656a6e9bfb28bf9034 to your computer and use it in GitHub Desktop.
Get `Object.prototype.toString()` to return JSON string without circular reference error
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