Skip to content

Instantly share code, notes, and snippets.

@hypesystem
Last active August 29, 2015 14:22
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 hypesystem/c8a1b1af33ef871932fa to your computer and use it in GitHub Desktop.
Save hypesystem/c8a1b1af33ef871932fa to your computer and use it in GitHub Desktop.
Insignificant Order Deep-Equals for Arrays and Objects in Javascript
function insignificantOrderDeepContains(haystack, needle) {
var matched = false;
haystack.forEach(function(straw) {
if(matched) return;
if(insignificantOrderDeepEquals(straw, needle)) {
matched = true;
}
});
return matched;
}
function insignificantOrderDeepEquals(obj1, obj2) {
var matching = true;
Object.keys(obj1).forEach(function(key) {
if(!matching) return;
if(typeof obj1[key] === "object" && obj1[key] != null) {
if(typeof obj2[key] !== "object" || obj2[key] == null) {
matching = false;
return;
}
matching = insignificantOrderDeepEquals(obj1[key], obj2[key]);
}
if(typeof obj1[key] === "array") {
if(typeof obj2[key] !== "array") {
matching = false;
return;
}
var innerMatching = true;
obj1[key].forEach(function(e) {
if(!innerMatching) return;
if(typeof e === "object" && e != null) {
innerMatching = insignificantOrderDeepContains(obj2[key], e);
return;
}
innerMatching = _.contains(obj2[key], e);
});
}
matching = obj1[key] === obj2[key];
});
return matching;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment