Skip to content

Commit 54f06b5

Browse files
feat: improved deepEqual()
1 parent 708acf2 commit 54f06b5

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/utils/deep-equal.ts

+17-10
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,34 @@
11
const isObject = (object: unknown): object is Record<string, unknown> => {
2-
return object !== null && typeof object === 'object'
2+
return object !== null && !Array.isArray(object) && typeof object === 'object'
33
}
44

55
const deepEqual = (object1: unknown, object2: unknown): boolean => {
6+
if (object1 === object2) {
7+
return true
8+
}
9+
10+
if (Array.isArray(object1) && Array.isArray(object2)) {
11+
if (object1.length !== object2.length) {
12+
return false
13+
}
14+
return object1.every((val, index) => deepEqual(val, object2[index]))
15+
}
16+
17+
if (Array.isArray(object1) !== Array.isArray(object2)) {
18+
return false
19+
}
20+
621
if (!isObject(object1) || !isObject(object2)) {
722
return object1 === object2
823
}
924

1025
const keys1 = Object.keys(object1)
1126
const keys2 = Object.keys(object2)
12-
1327
if (keys1.length !== keys2.length) {
1428
return false
1529
}
1630

17-
return keys1.every((key) => {
18-
const val1 = object1[key]
19-
const val2 = object2[key]
20-
if (isObject(val1) && isObject(val2)) {
21-
return deepEqual(val1, val2)
22-
}
23-
return val1 === val2
24-
})
31+
return keys1.every((key) => deepEqual(object1[key], object2[key]))
2532
}
2633

2734
export default deepEqual

0 commit comments

Comments
 (0)