JSFiddle - React, Tailwind, and code Playground
by Darker
HTML
<input type="button" onclick="showTests()" value="showTests" />
<pre id="tests">
</pre>
JavaScript
Object.prototype.equals = function(object2) {
//For the first loop, we only check for types
for (propName in this) {
//Check instance type
if (typeof this[propName] != typeof object2[propName]) {
//Different types => not equal
return false;
}
}
//Now a deeper check using other objects property names
for(propName in object2) {
//We must check instances anyway, there may be a property that only exists in object2
//I wonder, if remembering the checked values from the first loop would be faster or not
if (typeof this[propName] != typeof object2[propName]) {
//Different types => not equal
return false;
}
//Now the detail check and recursion
//This returns the script back to the array comparing
if (this[propName] instanceof Array && object2[propName] instanceof Array) {
// recurse into the nested arrays
if (!this[propName].compare(object2[propName]))
return false;
}
else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
// recurse into the nested arrays
if (!this[propName].equals(object2[propName]))
return false;
}
else if(this[propName] != object2[propName]) {
return false;
}
}
}
function showTests() {
var pre = document.getElementById("tests");
var data = "";
data += "({a:1, foo:\"bar\", numberOfTheBeast: 666}).equals({a:1, foo:\"bar\", numberOfTheBeast: 666})";
data += " - ";
data += ({a:1, foo:"bar", numberOfTheBeast: 666}).equals({a:1, foo:"bar", numberOfTheBeast: 666})?"true":"false";
pre.innerHTML = data;
}