Skip to content

Instantly share code, notes, and snippets.

@phanect
Created September 7, 2016 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phanect/8ec9c62f7144cc958b30ff5b778f9f8b to your computer and use it in GitHub Desktop.
Save phanect/8ec9c62f7144cc958b30ff5b778f9f8b to your computer and use it in GitHub Desktop.
/**
* Assert if objects are equal. This function also considers `not`
* @return true if obj1 and obj2 are equal, otherwise false
*/
function _objEquals(obj1, obj2) {
const keys1 = obj1.getOwnPropertyNames().sort(sortByCharCode),
keys2 = obj2.getOwnPropertyNames().sort(sortByCharCode),
sortByCharCode = function(key1, key2) {
if (key1 < key2) {
return -1;
} else if (key1 > key2) {
return 1;
} else {
return 0;
}
};
//
// Check keys are the same
//
if (keys1.length !== keys2.length) {
return false;
}
keys1.forEach(function(element, i) {
if (keys1[i] !== keys2[i]) {
return false;
}
});
//
// Check values
//
for (const key of obj1.getOwnPropertyNames()) {
const property1 = obj1[key],
property2 = obj2[key];
if (Array.isArray(property1)) {
property1.forEach(function(element, i) {
if (!this._objEquals(property1[i], property2[i])) {
return false;
}
});
} else if (typeof property1 === "object" && (property1.type === "not" || property2.type === "not")) {
// Should NOT be equal
if (property1.value === property2
|| property1 === property2.value
|| property1.value === property2.value
) {
return false;
}
} else if (typeof property1 === "object") {
if (!this._objEquals(property1, property2)) {
return false;
}
} else {
if (property1 !== property2) { // eslint-disable-line no-lonely-if
return false;
}
}
}
return true;
}
@phanect
Copy link
Author

phanect commented Jan 18, 2017

See also: Node.js's assert.deepStrictEqual()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment