Created
September 18, 2019 09:22
-
-
Save IvanofSA/e459a0c99f697090a254669573dc349c to your computer and use it in GitHub Desktop.
Сравнение объектов
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var objA = { | |
prop1: 'value1', | |
prop2: 'value2', | |
prop3: 'value3', | |
// prop7: ['value3', 'sd'], | |
prop4: { | |
subProp1: 'sub value1', | |
subProp2: { | |
subSubProp1: 'sub sub value1', | |
subSubProp2: [1, 2, {prop2: 1, prop: 2}, 4, 5] | |
} | |
}, | |
prop5: 1000, | |
prop6: new Date(2016, 2, 10) | |
}; | |
var objB = { | |
prop5: 1000, | |
prop1: 'value1', | |
prop2: 'value2', | |
prop6: new Date('2016/03/10'), | |
prop4: { | |
subProp2: { | |
subSubProp1: 'sub sub value1', | |
subSubProp2: [1, 2, {prop2: 1, prop: 2}, 4, 5] | |
}, | |
subProp1: 'sub value1' | |
} | |
}; | |
function deepEqual(a,b){ | |
var keysA = Object.keys(a); | |
var keysB = Object.keys(b); | |
var result = true; | |
// console.log('deepEqual', a,b) | |
keysA.forEach(function(key) { | |
// console.log(key) | |
result = result && equal(a[key], b[key]); | |
// console.log(result) | |
}) | |
// console.log(result); | |
return result; | |
} | |
function equal(a, b) { | |
// console.log('equal', a, b) | |
var typeA = getType(a), | |
typeB = getType(b); | |
if (typeA != typeB) { | |
return false; | |
} | |
switch (typeA) { | |
case 'object': | |
return deepEqual(a, b); | |
case 'array': | |
return eqArray(a, b); | |
case 'date': | |
return eqDate(a, b); | |
default: | |
return a === b; | |
} | |
}; | |
function getType(a) { | |
// console.log('getType', a) | |
if (typeof a === "object"){ | |
if(Array.isArray(a)){ | |
// console.log('array', a); | |
return 'array'; | |
} else if(a instanceof Date){ | |
return 'date'; | |
} else { | |
return 'object'; | |
} | |
} else { | |
return typeof a; | |
} | |
}; | |
function eqDate(dateA, dateB) { | |
return dateA.getTime() === dateB.getTime() | |
}; | |
function eqArray (a, b) { | |
if(!a.length === b.length){ | |
return false; | |
} | |
for (var i = 0; i < a.length; i++) { | |
if(getType(a[i])!==getType(b[i])) { | |
return false | |
} | |
if(!equal(a[i], b[i])) { | |
return false; | |
} | |
} | |
return true | |
} | |
console.log(deepEqual(objA, objB)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment