Created
October 28, 2014 13:20
-
-
Save alexandrusavin/8b9aca4bcbb6c208b548 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
module.exports = { | |
testIfArray: function (arr) { | |
return !!arr && Array.isArray(arr); | |
}, | |
testIfObject: function (obj) { | |
return !this.testIfArray(obj) && typeof obj === 'object'; | |
}, | |
compareObj: function (obj1, obj2, filterKeys) { | |
var isArray = false, isObject = false; | |
if (this.testIfArray(obj1) && this.testIfArray(obj2)) { | |
isArray = true; | |
} | |
if (this.testIfObject(obj1) && this.testIfObject(obj2)) { | |
isObject = true; | |
} | |
if (!isArray && !isObject && obj1 !== obj2) { | |
return false; | |
} | |
// Array testing | |
if (isArray) { | |
if (obj1.length !== obj2.length) | |
return false; | |
for (var i = 0; i < obj1.length; i++) { | |
if (!this.compareObj(obj1[i], obj2[i], filterKeys)) { | |
return false; | |
} | |
} | |
} | |
// Object testing | |
if (isObject) { | |
var keysObj1 = Object.keys(obj1); | |
var keysObj2 = Object.keys(obj2); | |
if (this.testIfArray(filterKeys)) { | |
function checkKey(el) { | |
return filterKeys.indexOf(el) === -1; | |
} | |
keysObj1 = keysObj1.filter(checkKey); | |
keysObj2 = keysObj2.filter(checkKey); | |
} | |
if (keysObj1.length !== keysObj2.length && !this.compareObj(keysObj1, keysObj2, filterKeys)) { | |
// if the array of object keys do not match than return | |
return false; | |
} | |
for (var i = 0; i < keysObj1.length; i++) { | |
var key = keysObj1[i]; | |
if (this.testIfArray(filterKeys) && filterKeys.indexOf(key) !== -1) { | |
// don't mind the values that need to be filtered out | |
break; | |
} | |
if (!this.compareObj(obj1[key], obj2[key], filterKeys)) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment