mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
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:
parent
f548963992
commit
ed526d074b
@ -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
|
||||
|
||||
@ -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' }
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user