Last active
April 4, 2017 15:33
-
-
Save rtm/4fa006c0bdcfdad32a87 to your computer and use it in GitHub Desktop.
JS deep equals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 /* TODO!! */; | |
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])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment