Skip to content

Commit

Permalink
feat: improved deepEqual()
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrieljablonski committed Feb 18, 2024
1 parent 708acf2 commit 54f06b5
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/utils/deep-equal.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
const isObject = (object: unknown): object is Record<string, unknown> => {
return object !== null && typeof object === 'object'
return object !== null && !Array.isArray(object) && typeof object === 'object'
}

const deepEqual = (object1: unknown, object2: unknown): boolean => {
if (object1 === object2) {
return true
}

if (Array.isArray(object1) && Array.isArray(object2)) {
if (object1.length !== object2.length) {
return false
}
return object1.every((val, index) => deepEqual(val, object2[index]))
}

if (Array.isArray(object1) !== Array.isArray(object2)) {
return false
}

if (!isObject(object1) || !isObject(object2)) {
return object1 === object2
}

const keys1 = Object.keys(object1)
const keys2 = Object.keys(object2)

if (keys1.length !== keys2.length) {
return false
}

return keys1.every((key) => {
const val1 = object1[key]
const val2 = object2[key]
if (isObject(val1) && isObject(val2)) {
return deepEqual(val1, val2)
}
return val1 === val2
})
return keys1.every((key) => deepEqual(object1[key], object2[key]))
}

export default deepEqual

0 comments on commit 54f06b5

Please sign in to comment.