@@ -3,39 +3,38 @@ import { pathToPointer } from './pathToPointer';
3
3
4
4
export function decycle ( obj : unknown , replacer ?: ( value : any ) => any ) {
5
5
const objs = new WeakMap < object , string > ( ) ;
6
+ const processedObjs = new WeakSet < object > ( ) ;
6
7
function derez ( value : any , path : ( string | number ) [ ] ) : any {
7
8
if ( replacer ) {
8
9
value = replacer ( value ) ;
9
10
}
10
-
11
11
if ( isPlainObject ( value ) || Array . isArray ( value ) ) {
12
12
// The path of an earlier occurance of value
13
13
const oldPath = objs . get ( value ) ;
14
-
15
14
// If the value is an object or array, look to see if we have already
16
15
// encountered it. If so, return a {"$ref":PATH} object.
17
16
if ( oldPath ) {
18
17
return { $ref : oldPath } ;
19
18
}
20
-
21
19
objs . set ( value , pathToPointer ( path ) ) ;
22
20
// If it is an array, replicate the array.
23
21
if ( Array . isArray ( value ) ) {
24
22
return value . map ( ( element , i ) => derez ( element , [ ...path , i ] ) ) ;
25
23
}
26
-
27
24
const newObj : Record < string , any > = { } ;
28
25
for ( const name in value ) {
29
26
if ( Object . prototype . hasOwnProperty . call ( value , name ) ) {
30
27
newObj [ name ] = derez ( value [ name ] , [ ...path , name ] ) ;
31
28
}
32
29
}
33
- // deleteing object before returing
34
- objs . delete ( value ) ;
30
+ // Only delete the object from the map if it has not been processed before
31
+ if ( ! processedObjs . has ( value ) ) {
32
+ objs . delete ( value ) ;
33
+ }
34
+ processedObjs . add ( value ) ;
35
35
return newObj ;
36
36
}
37
37
return value ;
38
38
}
39
-
40
39
return derez ( obj , [ ] ) ;
41
40
}
0 commit comments