Skip to content

Instantly share code, notes, and snippets.

@Mehuge
Created October 16, 2021 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mehuge/9e98eccdd346e3f847e1da403a38e261 to your computer and use it in GitHub Desktop.
Save Mehuge/9e98eccdd346e3f847e1da403a38e261 to your computer and use it in GitHub Desktop.
Strict deep compare javascript objects.
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