File tree Expand file tree Collapse file tree 2 files changed +32
-3
lines changed Expand file tree Collapse file tree 2 files changed +32
-3
lines changed Original file line number Diff line number Diff line change @@ -5,6 +5,19 @@ function isDate(obj) {
5
5
return obj instanceof Date
6
6
}
7
7
8
+ // Assumes both a and b are arrays!
9
+ // Handles when arrays are "sparse" (array.every(...) doesn't handle sparse)
10
+ function compareArrays ( a , b ) {
11
+ if ( a . length !== b . length ) {
12
+ return false
13
+ }
14
+ let equal = true
15
+ for ( let i = 0 ; equal && i < a . length ; i ++ ) {
16
+ equal = looseEqual ( a [ i ] , b [ i ] )
17
+ }
18
+ return equal
19
+ }
20
+
8
21
/**
9
22
* Check if two values are loosely equal - that is,
10
23
* if they are plain objects, do they have the same shape?
@@ -22,9 +35,7 @@ function looseEqual(a, b) {
22
35
aValidType = isArray ( a )
23
36
bValidType = isArray ( b )
24
37
if ( aValidType || bValidType ) {
25
- return aValidType && bValidType
26
- ? a . length === b . length && a . every ( ( e , i ) => looseEqual ( e , b [ i ] ) )
27
- : false
38
+ return aValidType && bValidType ? compareArrays ( a , b ) : false
28
39
}
29
40
aValidType = isObject ( a )
30
41
bValidType = isObject ( b )
Original file line number Diff line number Diff line change @@ -175,4 +175,22 @@ describe('looseEqual', () => {
175
175
expect ( looseEqual ( null , false ) ) . toBe ( false )
176
176
expect ( looseEqual ( undefined , false ) ) . toBe ( false )
177
177
} )
178
+
179
+ it ( 'compares sparse arrays correctly' , ( ) => {
180
+ // The following arrays all have a length of 3
181
+ // But the first two are "sparse"
182
+ const arr1 = [ ]
183
+ arr1 [ 2 ] = true
184
+ const arr2 = [ ]
185
+ arr2 [ 2 ] = true
186
+ const arr3 = [ false , false , true ]
187
+ const arr4 = [ undefined , undefined , true ]
188
+
189
+ expect ( looseEqual ( arr1 , arr2 ) ) . toBe ( true )
190
+ expect ( looseEqual ( arr2 , arr1 ) ) . toBe ( true )
191
+ expect ( looseEqual ( arr1 , arr3 ) ) . toBe ( false )
192
+ expect ( looseEqual ( arr3 , arr1 ) ) . toBe ( false )
193
+ expect ( looseEqual ( arr1 , arr4 ) ) . toBe ( true )
194
+ expect ( looseEqual ( arr4 , arr1 ) ) . toBe ( true )
195
+ } )
178
196
} )
You can’t perform that action at this time.
0 commit comments