Skip to content

Instantly share code, notes, and snippets.

@Floofies
Created October 26, 2018 06:37
Show Gist options
  • Save Floofies/20fe6d74e3dc02f55e20ddbd0c57d4a8 to your computer and use it in GitHub Desktop.
Save Floofies/20fe6d74e3dc02f55e20ddbd0c57d4a8 to your computer and use it in GitHub Desktop.
Returns true if obj1 differs in any way from obj2
// Returns true if obj1 differs in any way from obj2
function testDiff(obj1, obj2) {
if (obj1 === null) return obj1 !== obj2;
const stack = [{ obj1: obj1, obj2: obj2 }];
const seen = new Map();
seen.set(obj1, stack[0]);
_objects: while (stack.length !== 0) {
const objects = stack.pop();
if (Array.isArray(objects.obj1) !== Array.isArray(objects.obj2)) return true;
const props1 = Object.keys(objects.obj1);
const props2 = Object.keys(objects.obj2);
if (props1.length === 0 && props2.length === 0) continue;
if (props1.length !== props2.length) return true;
if (!props1.every(value => props2.includes(value))) return true;
if (!props2.every(value => props1.includes(value))) return true;
_props: for (var loc = 0; loc < props1.length; loc++) {
const prop = props1[loc];
const value1 = objects.obj1[prop];
const value2 = objects.obj2[prop];
if ((typeof value1) !== (typeof value2)) return true;
if ((typeof value1) === "object") {
if (value1 === null) {
if (obj1 !== obj2) return true;
continue _props;
}
if (seen.has(value1)) continue _props;
stack.push({ obj1: value1, obj2: value2 });
seen.set(value1, objects);
continue _props;
}
if (Number.isNaN(value1) !== Number.isNaN(value2)) return true;
if (value1 !== value2) return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment