Last active
May 21, 2024 18:33
-
-
Save cynthia2006/90c7e2b6f7b2446940729cf1e796b2ee to your computer and use it in GitHub Desktop.
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
function objectEqualRecursiveDeep(a, b) { | |
if (a == b) | |
return true; | |
if (typeof a != typeof b) | |
return false; | |
// TODO do something about undefined. | |
if (a == null && b != null || a != null && b == null) | |
return false; | |
else if (a == null && b == null) | |
return true; | |
function arrayEqual(a, b) { | |
if (a.length != b.length) | |
return false; | |
for (var i = 0; i < a.length; ++i) | |
if (a[i] != b[i]) | |
return false; | |
return true; | |
} | |
if (!arrayEqual(Object.getOwnPropertyNames(a), Object.getOwnPropertyNames(b))) | |
return false; | |
if (!arrayEqual(Object.getOwnPropertySymbols(a), Object.getOwnPropertySymbols(b))) | |
return false; | |
function equalRecursive(a, b) { | |
// Equal by reference (optimization) | |
if (a == b) | |
return true; | |
if (typeof a != typeof b) | |
return false; | |
if (typeof a == 'object') { | |
if (!objectEqualRecursiveDeep(a, b)) | |
return false; | |
} else { | |
// Comparing primitives | |
if (a != b) | |
return false; | |
} | |
return true; | |
} | |
for (var property of Object.getOwnPropertyNames(a)) | |
if (!equalRecursive(a[property], b[property])) | |
return false; | |
for (var symbol of Object.getOwnPropertySymbols(a)) | |
if (!equalRecursive(a[symbol], b[symbol])) | |
return false; | |
if (!objectEqualRecursiveDeep(Object.getPrototypeOf(a), Object.getPrototypeOf(b))) | |
return false; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How is this structural equality useful? One great is example is this.