I have found this (personally) convenient answer that fits my needs: https://stackoverflow.com/a/6713782/2678218
But since I am using TypeScript, I can have something like this with Generics:
private equals<T>(x: T, y: T) {
if (x === y) {
return true; // if both x and y are null or undefined and exactly the same
} else if (!(x instanceof Object) || !(y instanceof Object)) {
return false; // if they are not strictly equal, they both need to be Objects
} else if (x.constructor !== y.constructor) {
// they must have the exact same prototype chain, the closest we can do is
// test their constructor.
return false;
} else {
for (const p in x) {
if (!x.hasOwnProperty(p)) {
continue; // other properties were tested using x.constructor === y.constructor
}
if (!y.hasOwnProperty(p)) {
return false; // allows to compare x[ p ] and y[ p ] when set to undefined
}
if (x[p] === y[p]) {
continue; // if they have the same strict value or identity then they are equal
}
if (typeof (x[p]) !== 'object') {
return false; // Numbers, Strings, Functions, Booleans must be strictly equal
}
if (!this.equals(x[p], y[p])) {
return false;
}
}
for (const p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
return false;
}
}
return true;
}
}
I'm sure that since we're using <T>
here, we can refactor the code. One thing's for sure is by removing some if
statements that are not needed anymore. But i am not confident of which to take away and also not sure if there will be a more optimal code for this. So I'll leave the question here and have everyone vote for the best answer.
In this context, what I actually mean by equality of two objects is when two objects of the same type have equal values of every property.