-
-
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.
Fix a false-positive for circular object
Fixes #2
- Loading branch information
1 parent
587d7f8
commit 566526e
Showing
5 changed files
with
71 additions
and
16 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,24 +1,19 @@ | ||
const makeCircularReplacer = () => { | ||
const seen = new WeakSet(); | ||
const seen = new WeakMap(); | ||
|
||
return (key, value) => { | ||
if (value !== null && typeof value === 'object') { | ||
if (seen.has(value)) { | ||
if (seen.has(value) && seen.get(value) !== key) { | ||
return '[Circular]'; | ||
} | ||
|
||
seen.add(value); | ||
seen.set(value, key); | ||
} | ||
|
||
return value; | ||
}; | ||
}; | ||
|
||
export default function safeStringify(object, {indentation} = {}) { | ||
// Without this, the replacer would replace duplicate objects in a top-level array. | ||
if (Array.isArray(object)) { | ||
object = object.map(element => JSON.parse(JSON.stringify(element, makeCircularReplacer()))); | ||
} | ||
|
||
return JSON.stringify(object, makeCircularReplacer(), 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
Binary file not shown.