Skip to content

Commit

Permalink
fix(util/loose-equal): handle comparing sparse arrays (#2813)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmorehouse committed Mar 11, 2019
1 parent a23c53f commit 6ac8ade
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/utils/loose-equal.js
Expand Up @@ -5,6 +5,19 @@ function isDate(obj) {
return obj instanceof Date
}

// Assumes both a and b are arrays!
// Handles when arrays are "sparse" (array.every(...) doesn't handle sparse)
function compareArrays(a, b) {
if (a.length !== b.length) {
return false
}
let equal = true
for (let i = 0; equal && i < a.length; i++) {
equal = looseEqual(a[i], b[i])
}
return equal
}

/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
Expand All @@ -22,9 +35,7 @@ function looseEqual(a, b) {
aValidType = isArray(a)
bValidType = isArray(b)
if (aValidType || bValidType) {
return aValidType && bValidType
? a.length === b.length && a.every((e, i) => looseEqual(e, b[i]))
: false
return aValidType && bValidType ? compareArrays(a, b) : false
}
aValidType = isObject(a)
bValidType = isObject(b)
Expand Down
18 changes: 18 additions & 0 deletions src/utils/loose-equal.spec.js
Expand Up @@ -175,4 +175,22 @@ describe('looseEqual', () => {
expect(looseEqual(null, false)).toBe(false)
expect(looseEqual(undefined, false)).toBe(false)
})

it('compares sparse arrays correctly', () => {
// The following arrays all have a length of 3
// But the first two are "sparse"
const arr1 = []
arr1[2] = true
const arr2 = []
arr2[2] = true
const arr3 = [false, false, true]
const arr4 = [undefined, undefined, true]

expect(looseEqual(arr1, arr2)).toBe(true)
expect(looseEqual(arr2, arr1)).toBe(true)
expect(looseEqual(arr1, arr3)).toBe(false)
expect(looseEqual(arr3, arr1)).toBe(false)
expect(looseEqual(arr1, arr4)).toBe(true)
expect(looseEqual(arr4, arr1)).toBe(true)
})
})

0 comments on commit 6ac8ade

Please sign in to comment.