Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Last active October 17, 2017 15:58
Show Gist options
  • Save C-Rodg/8c463d313998e83d2495f004c6f08bee to your computer and use it in GitHub Desktop.
Save C-Rodg/8c463d313998e83d2495f004c6f08bee to your computer and use it in GitHub Desktop.
A function to fully compare objects and arrays.
const isEqual = (value, other) => {
// Tests - same object type, same length, same items
const type = Object.prototype.toString.call(value);
if (type !== Object.prototype.toString.call(other)) {
return false;
}
if (['[object Array]', '[object Object]'].indexOf(type) < 0) {
return false;
}
const valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
const otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
if (valueLen !== otherLen) {
return false;
}
if (type === '[object Array]') {
for (let i = 0; i < valueLen; i++) {
// Compare Item
if (compare(value[i], other[i]) === false) {
return false;
}
}
} else {
for (let key in value) {
if (value.hasOwnProperty(key)) {
// Compare item
if(compare(value[key], other[key]) === false) {
return false;
}
}
}
}
// No tests failed, return true
return true;
};
// Compare two items
const compare = (item1, item2) => {
const itemType = Object.prototype.toString.call(item1);
if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
if (!isEqual(item1, item2)) {
return false;
}
} else {
if (itemType !== Object.prototype.toString.call(item2)) {
return false;
}
if (itemType === '[object Function]') {
if (item1.toString() !== item2.toString()) {
return false;
}
} else {
if (item1 !== item2) {
return false;
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment