Skip to content

Commit 6029a10

Browse files
committed
Better cycles detection
1 parent fa72817 commit 6029a10

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

lib/index.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ function stringifyDeterministic (obj, opts = DEFAULTS) {
2828
}
2929
})(opts.compare)
3030

31+
// Detect circular structure in obj and raise error efficiently.
32+
if (!cycles) stringify(obj)
33+
3134
const seen = []
3235

3336
return (function _deterministic (parent, key, node, level) {
@@ -49,11 +52,12 @@ function stringifyDeterministic (obj, opts = DEFAULTS) {
4952
}
5053
return '[' + out.join(',') + indent + ']'
5154
} else {
52-
if (seen.indexOf(node) !== -1) {
53-
if (cycles) return stringify('[Circular]')
54-
throw new TypeError('Converting circular structure to JSON')
55-
} else {
56-
seen.push(node)
55+
if (cycles) {
56+
if (seen.indexOf(node) !== -1) {
57+
return stringify('[Circular]')
58+
} else {
59+
seen.push(node)
60+
}
5761
}
5862

5963
const nodeKeys = keys(node).sort(compare && compare(node))

0 commit comments

Comments
 (0)