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) { static deepEquals(a, b) {
if (obj1 === null && obj2 === null) { if (a === b) return true;
return true;
}
if (obj1 === null || obj2 === null) {
return false;
}
if (obj1 === obj2) { if (a && b && typeof a == 'object' && typeof b == 'object') {
delete obj1._$visited; var arrA = Array.isArray(a)
return true; , arrB = Array.isArray(b)
} , i
, length
, key;
if (typeof obj1 === 'object' && typeof obj2 === 'object') { if (arrA && arrB) {
obj1._$visited = true; length = a.length;
for (var p in obj1) { if (length != b.length) return false;
if (p === "_$visited") continue; for (i = length; i-- !== 0;)
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) { if (!this.deepEquals(a[i], b[i])) return false;
return false; return true;
}
switch (typeof (obj1[p])) {
case 'object':
if ((obj1[p] && obj1[p]._$visited) || !this.equals(obj1[p], obj2[p])) return false;
break;
case 'function':
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) {