Created
April 8, 2022 19:17
-
-
Save hawkeye64/f0fc1c4721a76986ee1049b428ceb61f to your computer and use it in GitHub Desktop.
JavaScript to compare two things as equal (client-side)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
export function deepEqual (object1, object2) { | |
// check for falsy values | |
if (!object1 && !object2) return true | |
if (!object1 && object2) return false | |
if (object1 && !object2) return false | |
const keys1 = Object.keys(object1) | |
const keys2 = Object.keys(object2) | |
if (keys1.length !== keys2.length) { | |
return false | |
} | |
for (const key of keys1) { | |
const val1 = object1[ key ] | |
const val2 = object2[ key ] | |
const areObjects = isObject(val1) && isObject(val2) | |
if ( | |
(areObjects && !deepEqual(val1, val2)) | |
|| (!areObjects && val1 !== val2) | |
) { | |
return false | |
} | |
} | |
return true | |
} | |
function isObject (object) { | |
return object != null && typeof object === 'object' | |
} | |
export default deepEqual |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment