-
-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
6 changed files
with
334 additions
and
28 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,28 @@ | ||
const makeCircularReplacer = () => { | ||
const seen = new WeakMap(); | ||
|
||
return (key, value) => { | ||
function safeStringifyReplacer(seen) { | ||
return function (key, value) { | ||
if (value !== null && typeof value === 'object') { | ||
if (seen.has(value) && seen.get(value) !== key) { | ||
if (seen.has(value)) { | ||
return '[Circular]'; | ||
} | ||
|
||
seen.set(value, key); | ||
seen.add(value); | ||
|
||
const newValue = Array.isArray(value) ? [] : {}; | ||
|
||
for (const [key2, value2] of Object.entries(value)) { | ||
newValue[key2] = safeStringifyReplacer(seen)(key2, value2); | ||
} | ||
|
||
seen.delete(value); | ||
|
||
return newValue; | ||
} | ||
|
||
return value; | ||
}; | ||
}; | ||
} | ||
|
||
export default function safeStringify(object, {indentation} = {}) { | ||
return JSON.stringify(object, makeCircularReplacer(), indentation); | ||
const seen = new WeakSet(); | ||
return JSON.stringify(object, safeStringifyReplacer(seen), indentation); | ||
} |
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
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
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
Oops, something went wrong.