Skip to content

Instantly share code, notes, and snippets.

@cynthia2006
Last active May 21, 2024 18:33
Show Gist options
  • Save cynthia2006/90c7e2b6f7b2446940729cf1e796b2ee to your computer and use it in GitHub Desktop.
Save cynthia2006/90c7e2b6f7b2446940729cf1e796b2ee to your computer and use it in GitHub Desktop.
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;
}
@cynthia2006
Copy link
Author

How is this structural equality useful? One great is example is this.

var base1 = {property1: 1, property2: 2};
var base2 = {property1: 1};

var derived1 = Object.create(base1);
derived1.ownProperty1 = 1;
derived1.ownProperty2 = 2;

var derived2 = Object.create(base2);
derived2.ownProperty1 = 1;
derived2.ownProperty2 = 2;

objectEqualRecursiveDeep(derived1, derived2); // false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment