@@ -7,35 +7,18 @@ import { ee } from '../event-emitter/contextual-ee'
77
88/**
99 * Returns a function for use as a replacer parameter in JSON.stringify() to handle circular references.
10- * Uses an array to track the current ancestor chain, allowing the same object to appear
11- * multiple times in the structure as long as it's not a circular reference.
1210 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value MDN - Cyclical object value }
13- * @returns {Function } A function that filters out circular references while allowing duplicate references .
11+ * @returns {Function } A function that filters out values it has seen before .
1412 */
1513const getCircularReplacer = ( ) => {
16- const stack = [ ]
17-
18- return function ( key , value ) {
19- if ( stack . length > 0 ) {
20- // Find where we are in the stack
21- const thisPos = stack . indexOf ( this )
22- if ( ~ thisPos ) {
23- // We're still in the stack, trim it
24- stack . splice ( thisPos + 1 )
25- } else {
26- // We're not in the stack, add ourselves
27- stack . push ( this )
28- }
29-
30- // Check if value is in the current ancestor chain
31- if ( ~ stack . indexOf ( value ) ) {
14+ const seen = new WeakSet ( )
15+ return ( key , value ) => {
16+ if ( typeof value === 'object' && value !== null ) {
17+ if ( seen . has ( value ) ) {
3218 return
3319 }
34- } else {
35- // First call, initialize with root
36- stack . push ( value )
20+ seen . add ( value )
3721 }
38-
3922 return value
4023 }
4124}
0 commit comments