Skip to content

Instantly share code, notes, and snippets.

@yashshah1
Created May 20, 2020 19:20
Show Gist options
  • Select an option

  • Save yashshah1/e34667cb5fbd136a02305764d5f2b9f2 to your computer and use it in GitHub Desktop.

Select an option

Save yashshah1/e34667cb5fbd136a02305764d5f2b9f2 to your computer and use it in GitHub Desktop.
It's a CommonJS function that checks if two JS Objects are the same, checks nested objects as well
/**
* Designed to work only if the object is an output of JSON.parse(obj)
* So Only allowed datatypes for value are: number, string, boolean, object and null
*/
"use strict";
function deepCompare(obj1, obj2) {
var leftChain, rightChain;
function compare2Objects(x, y) {
if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number')
return true;
if (x === y)
return true;
if (!(x instanceof Object && y instanceof Object))
return false;
if (x.isPrototypeOf(y) || y.isPrototypeOf(x))
return false;
if (x.constructor !== y.constructor)
return false;
if (x.prototype !== y.prototype)
return false;
if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1)
return false;
for (var p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p))
return false;
else if (typeof y[p] !== typeof x[p])
return false;
}
for (var p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p))
return false;
else if (typeof y[p] !== typeof x[p])
return false;
switch (typeof x[p]) {
case 'object':
leftChain.push(x);
rightChain.push(y);
if (!compare2Objects(x[p], y[p]))
return false;
leftChain.pop();
rightChain.pop();
break;
default:
if (x[p] !== y[p])
return false;
break;
}
}
return true;
}
return compare2Objects(obj1, obj2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment