Created
October 16, 2021 11:29
-
-
Save Mehuge/9e98eccdd346e3f847e1da403a38e261 to your computer and use it in GitHub Desktop.
Strict deep compare javascript objects.
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 compare(a,b) { | |
if (typeof a != typeof b) return false; | |
function compareObjects(a, b) { | |
const ka = Object.keys(a); | |
const kb = Object.keys(b); | |
if (ka.length != kb.length) return false; | |
for (let k of ka) { | |
if (!(k in b) || !compare(a[k], b[k])) return false; | |
} | |
return true; | |
} | |
function compareArrays(a, b) { | |
if (a.length != b.length) return false; | |
for (let i = 0; i < a.length; i++) { | |
if (!compare(a[i], b[i])) return false; | |
} | |
} | |
if (Array.isArray(a) && Array.isArray(b)) { | |
return compareArrays(a, b); | |
} | |
if (typeof a == "object") { | |
return compareObjects(a, b); | |
} | |
return Object.is(a, b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment