Better deep equals check, will port it to NG and React as well

pull/3/head
cagataycivici 2018-12-09 01:14:46 +03:00
parent 732b2d988b
commit 6be1afe855
1 changed files with 41 additions and 38 deletions

View File

@ -4,55 +4,58 @@ export default class ObjectUtils {
if(field) if(field)
return (this.resolveFieldData(obj1, field) === this.resolveFieldData(obj2, field)); return (this.resolveFieldData(obj1, field) === this.resolveFieldData(obj2, field));
else else
return this.equalsByValue(obj1, obj2); return this.deepEquals(obj1, obj2);
} }
static equalsByValue(obj1, obj2) {
if (obj1 === null && obj2 === null) {
return true;
}
if (obj1 === null || obj2 === null) {
return false;
}
if (obj1 === obj2) { static deepEquals(a, b) {
delete obj1._$visited; if (a === b) return true;
return true;
}
if (typeof obj1 === 'object' && typeof obj2 === 'object') { if (a && b && typeof a == 'object' && typeof b == 'object') {
obj1._$visited = true; var arrA = Array.isArray(a)
for (var p in obj1) { , arrB = Array.isArray(b)
if (p === "_$visited") continue; , i
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) { , length
return false; , key;
}
switch (typeof (obj1[p])) { if (arrA && arrB) {
case 'object': length = a.length;
if ((obj1[p] && obj1[p]._$visited) || !this.equals(obj1[p], obj2[p])) return false; if (length != b.length) return false;
break; for (i = length; i-- !== 0;)
if (!this.deepEquals(a[i], b[i])) return false;
case 'function': return true;
if (typeof (obj2[p]) === 'undefined' || (p !== 'compare' && obj1[p].toString() !== obj2[p].toString())) return false;
break;
default:
if (obj1[p] !== obj2[p]) return false;
break;
}
} }
for (var pp in obj2) { if (arrA != arrB) return false;
if (typeof (obj1[pp]) === 'undefined') return false;
var dateA = a instanceof Date
, dateB = b instanceof Date;
if (dateA != dateB) return false;
if (dateA && dateB) return a.getTime() == b.getTime();
var regexpA = a instanceof RegExp
, regexpB = b instanceof RegExp;
if (regexpA != regexpB) return false;
if (regexpA && regexpB) return a.toString() == b.toString();
var keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length)
return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
key = keys[i];
if (!this.deepEquals(a[key], b[key])) return false;
} }
delete obj1._$visited;
return true; return true;
} }
return false; return a !== a && b !== b;
} };
static resolveFieldData(data, field) { static resolveFieldData(data, field) {
if(data && field) { if(data && field) {