Last active
August 29, 2015 14:23
-
-
Save clemgrim/ccb5580f9c2da310071f to your computer and use it in GitHub Desktop.
This file contains 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
// check if two values are equals (deep check) | |
function deepEquals(value, other) { | |
// first, check type | |
var areEquals = typeof value === typeof other; | |
if (areEquals) { | |
if (value instanceof Array && other instanceof Array) { // handle arrays | |
areEquals = other.length === value.length; | |
if (areEquals) { | |
value.forEach(function (rec, i) { | |
return areEquals = deepEquals(value[i], other[i]); | |
}); | |
} | |
} else if (typeof value === 'object') { // handle objects | |
// check object class | |
areEquals = other.constructor === value.constructor; | |
if (areEquals) { | |
var key, keys = []; | |
for (key in value) { | |
areEquals = deepEquals(value[key], other[key]); | |
if (!areEquals) break; | |
keys.push(key); | |
} | |
// we have to process both variables | |
// the second object may have more properties | |
if (areEquals) { | |
for (key in other) { | |
if (keys.indexOf(key) === -1) { | |
areEquals = deepEquals(value[key], other[key]); | |
if (!areEquals) break; | |
keys.push(key); | |
} | |
} | |
} | |
} | |
} else { | |
// otherwise, strict comparison | |
areEquals = value === other; | |
} | |
} | |
return areEquals; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment