feat(shallow): Add support of Maps and Sets to shallow comparator (#1451)

* Add support of Maps and Sets to shallow comparator.

* Update src/shallow.ts

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
This commit is contained in:
Anton 2022-12-05 04:28:28 -08:00 committed by GitHub
parent f548963992
commit ed526d074b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 60 additions and 0 deletions

View File

@ -10,6 +10,29 @@ function shallow<T>(objA: T, objB: T) {
) {
return false
}
if (objA instanceof Map && objB instanceof Map) {
if (objA.size !== objB.size) return false
for (const [key, value] of objA) {
if (!Object.is(value, objB.get(key))) {
return false
}
}
return true
}
if (objA instanceof Set && objB instanceof Set) {
if (objA.size !== objB.size) return false
for (const value of objA) {
if (!objB.has(value)) {
return false
}
}
return true
}
const keysA = Object.keys(objA)
if (keysA.length !== Object.keys(objB).length) {
return false

View File

@ -39,6 +39,43 @@ describe('shallow', () => {
expect(shallow([{ foo: 'bar' }], [{ foo: 'bar', asd: 123 }])).toBe(false)
})
it('compares Maps', () => {
function createMap<T extends object>(obj: T) {
return new Map(Object.entries(obj))
}
expect(
shallow(
createMap({ foo: 'bar', asd: 123 }),
createMap({ foo: 'bar', asd: 123 })
)
).toBe(true)
expect(
shallow(
createMap({ foo: 'bar', asd: 123 }),
createMap({ foo: 'bar', foobar: true })
)
).toBe(false)
expect(
shallow(
createMap({ foo: 'bar', asd: 123 }),
createMap({ foo: 'bar', asd: 123, foobar: true })
)
).toBe(false)
})
it('compares Sets', () => {
expect(shallow(new Set(['bar', 123]), new Set(['bar', 123]))).toBe(true)
expect(shallow(new Set(['bar', 123]), new Set(['bar', 2]))).toBe(false)
expect(shallow(new Set(['bar', 123]), new Set(['bar', 123, true]))).toBe(
false
)
})
it('compares functions', () => {
function firstFnCompare() {
return { foo: 'bar' }