-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshallow.ts
46 lines (40 loc) · 959 Bytes
/
shallow.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Shallow compare 2 values.
*/
export const shallow = <T>(a: T, b: T) => {
if (Object.is(a, b)) {
return true
}
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
return false
}
if (a instanceof Map && b instanceof Map) {
if (a.size !== b.size) return false
for (const [key, value] of a) {
if (!Object.is(value, b.get(key))) {
return false
}
}
return true
}
if (a instanceof Set && b instanceof Set) {
if (a.size !== b.size) return false
for (const value of a) {
if (!b.has(value)) return false
}
return true
}
const keysA = Object.keys(a) as (keyof T)[]
if (keysA.length !== Object.keys(b).length) {
return false
}
for (let i = 0; i < keysA.length; i++) {
if (
!Object.prototype.hasOwnProperty.call(b, keysA[i]) ||
!Object.is(a[keysA[i]], b[keysA[i]])
) {
return false
}
}
return true
}