Skip to content

Instantly share code, notes, and snippets.

@hrishikeshs
Forked from rtm/deep-equals.js
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save hrishikeshs/ac19bfec44d67c2049c0 to your computer and use it in GitHub Desktop.

Select an option

Save hrishikeshs/ac19bfec44d67c2049c0 to your computer and use it in GitHub Desktop.
function deepEquals(x, y) {
if (x === y) return true;
if (x !== x) return y !== y;
if (typeof x !== typeof y) return false;
if (typeof x !== 'object') return false;
var typeX = getType(x);
var typeY = getType(y);
if (typeX !== typeY) return false;
if (typeX === 'date' ) return +x === +y;
if (typeX === 'array' ) return deepEqualsArray(x, y);
if (typeX === 'regexp') return ((x + "") === (y + ""));
if (typeX === 'object') return deepEqualsObject(a, b);
return false;
}
function deepEqualsArray(x, y) {
return x.length === y.length &&
x.every((xx, i) => deepEquals(xx, y[i]));
}
function getType(x) {
var type = Object.prototype.toString.call(x);
return type.substring(8, type.length - 1 ).toLowerCase();
}
function deepEqualsObjects(x, y) {
var keysX = Object.keys(x);
var keysY = Object.keys(y);
return deepEqualsArray(keysX.sort(), keysY.sort()) &&
keysX.every(k => deepEquals(x[k], y[k]));
}
console.log(deepEquals(NaN, NaN));
console.log(deepEquals(1, 1));
console.log(deepEquals(1, 2));
console.log(deepEquals([1,2], [1,2]));
console.log(deepEquals([1,2], [1,3]));
console.log(deepEquals(/abc+\/\/\/\gA*/, new RegExp(/abc+\/\/\/\gA*/)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment