@@ -3,11 +3,15 @@ interface Difference {
3
3
path : string [ ] ;
4
4
value ?: any ;
5
5
}
6
+ interface Options {
7
+ cyclesFix : boolean ;
8
+ }
6
9
const t = true ;
7
10
const richTypes = { Date : t , RegExp : t , String : t , Number : t } ;
8
11
export default function diff (
9
12
obj : Record < string , any > | any [ ] ,
10
13
newObj : Record < string , any > | any [ ] ,
14
+ options : Partial < Options > = { cyclesFix : true } ,
11
15
stack : Record < string , any > [ ] = [ ]
12
16
) : Difference [ ] {
13
17
let diffs : Difference [ ] = [ ] ;
@@ -17,35 +21,44 @@ export default function diff(
17
21
type : "REMOVE" ,
18
22
path : [ key ] ,
19
23
} ) ;
20
- } else if (
21
- obj [ key ] &&
22
- newObj [ key ] &&
23
- typeof obj [ key ] === "object" &&
24
- typeof newObj [ key ] === "object" &&
25
- ! richTypes [ Object . getPrototypeOf ( obj [ key ] ) . constructor . name ] &&
26
- ! stack . includes ( obj [ key ] )
24
+ continue ;
25
+ }
26
+ const objKey = obj [ key ] ;
27
+ const newObjKey = newObj [ key ] ;
28
+ const areObjects =
29
+ typeof objKey === "object" && typeof newObjKey === "object" ;
30
+ if (
31
+ objKey &&
32
+ newObjKey &&
33
+ areObjects &&
34
+ ! richTypes [ Object . getPrototypeOf ( objKey ) . constructor . name ] &&
35
+ ( options . cyclesFix ? ! stack . includes ( obj [ key ] ) : true )
27
36
) {
28
- const nestedDiffs = diff ( obj [ key ] , newObj [ key ] , stack . concat ( [ obj [ key ] ] ) ) ;
29
- diffs . push (
30
- ...nestedDiffs . map ( ( difference ) => {
37
+ const nestedDiffs = diff (
38
+ objKey ,
39
+ newObjKey ,
40
+ options ,
41
+ options . cyclesFix ? stack . concat ( [ objKey ] ) : [ ]
42
+ ) ;
43
+ diffs . push . apply (
44
+ nestedDiffs . map ( ( difference ) => {
31
45
difference . path . unshift ( key ) ;
32
46
return difference ;
33
47
} )
34
48
) ;
35
49
} else if (
36
- obj [ key ] !== newObj [ key ] &&
50
+ objKey !== newObjKey &&
37
51
! (
38
- typeof obj [ key ] === "object" &&
39
- typeof newObj [ key ] === "object" &&
40
- ( isNaN ( obj [ key ] )
41
- ? obj [ key ] + "" === newObj [ key ] + ""
42
- : + obj [ key ] === + newObj [ key ] )
52
+ areObjects &&
53
+ ( isNaN ( objKey )
54
+ ? objKey + "" === newObjKey + ""
55
+ : + objKey === + newObjKey )
43
56
)
44
57
) {
45
58
diffs . push ( {
46
59
path : [ key ] ,
47
60
type : "CHANGE" ,
48
- value : newObj [ key ] ,
61
+ value : newObjKey ,
49
62
} ) ;
50
63
}
51
64
}
0 commit comments