JSFiddle - React, Tailwind, and code Playground
by maremp
JavaScript
Object.prototype.equals = function (obj, thisParents, objParents) {
"use strict";
var i;
// null and undefined won't have this function in their prototype
// so it's safe to conclude that any other object is not equal to them
if (obj === undefined || obj === null) {
return false;
}
// compare primitives
// in case of 'test'.equals('test') typeof(this) is 'object'
// and typeof(obj) is 'string', so compare by value
if (typeof (obj) !== 'object' && this.constructor === obj.constructor) {
return this.valueOf() === obj.valueOf();
}
// if objects are of different types or lengths they can't be equal
if (this.constructor !== obj.constructor || (this.length !== undefined && this.length !== obj.length)) {
return false;
}
for (i in this) {
// build the parents list for objects on the left (this)
if (thisParents === undefined) thisParents = [];
if (this.constructor === Object) thisParents.push(this);
// build the parents list for object on the right (obj)
if (objParents === undefined) objParents = [];
if (this.constructor === Object) objParents.push(obj);
// walk through object properties
if (this.propertyIsEnumerable(i)) {
if (obj.propertyIsEnumerable(i)) {
// if object at i was met while going down here
// it's a self reference
if ((this[i].constructor === Object && thisParents.indexOf(this[i]) >= 0) || (obj[i].constructor === Object && objParents.indexOf(obj[i]) >= 0)) {
return this[i] === obj[i];
}
try {
if (!this[i].equals(obj[i], thisParents, objParents)) {
return false;
}
} catch (e) {
// you're here if 'this' is null or undefined
if (this[i] !== obj[i]) {
return...