Last active
November 3, 2022 04:44
-
-
Save iambriansreed/3bd758b198379aa43fd5fa937532e5e1 to your computer and use it in GitHub Desktop.
isEqualish - deep-equal but ignores array order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import isEqualish from './isEqualish'; | |
describe('compare', () => { | |
it('arrays should be true when different order', () => { | |
const obj1 = { x: 1, y: 2 }; | |
const obj2 = { x: 3, y: 4 }; | |
const a = [obj1, obj2]; | |
const b = [obj2, obj1]; | |
expect(isEqualish(a, b)).toBeTruthy(); | |
}); | |
it('different objects should be false', () => { | |
const obj1 = { x: 1, y: 2 }; | |
const obj2 = { x: 3, y: 4 }; | |
expect(isEqualish(obj1, obj2)).toBeFalsy(); | |
}); | |
it('objects with arrays should be true', () => { | |
const obj1 = { x: 1, y: [1, 2, 3] }; | |
const obj2 = { x: 1, y: [1, 2, 3] }; | |
expect(isEqualish(obj1, obj2)).toBeTruthy(); | |
}); | |
it('objects with arrays in different order should be true', () => { | |
const obj1 = { x: 1, y: [1, 2, 3] }; | |
const obj2 = { x: 1, y: [2, 1, 3] }; | |
expect(isEqualish(obj1, obj2)).toBeTruthy(); | |
}); | |
it('objects with different array lengths should false', () => { | |
const obj1 = { x: 1, y: [1, 2, 3] }; | |
const obj2 = { x: 1, y: [2, 1, 3, 4] }; | |
expect(isEqualish(obj1, obj2)).toBeFalsy(); | |
}); | |
it('objects with different array values should false', () => { | |
const obj1 = { x: 1, y: [1, 2, 3] }; | |
const obj2 = { x: 1, y: [2, 1, 4] }; | |
expect(isEqualish(obj1, obj2)).toBeFalsy(); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import isDeepEqual from 'deep-equal'; | |
export default function isEqualish<T = any>( | |
a: T | undefined, | |
b: T | undefined | |
): boolean { | |
if (!!a !== !!b) return false; | |
if (!a) return true; | |
if (!b) return true; | |
if (Array.isArray(a) && Array.isArray(b)) { | |
if (a.length !== b.length) return false; | |
return a.every((aValue) => | |
b.some((bValue) => isDeepEqual(aValue, bValue)) | |
); | |
} | |
if (typeof b === 'object' && typeof a === 'object') { | |
return Object.entries(a).every(([key, aValue]) => { | |
if (key in b) { | |
// @ts-ignore | |
const bValue = b[key]; | |
return isEqualish(aValue, bValue); | |
} | |
return false; | |
}); | |
} | |
return isDeepEqual(a, b, { strict: false }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment