Created
October 7, 2013 14:44
-
-
Save oaleynik/6869189 to your computer and use it in GitHub Desktop.
Deep Equality from Mongoose
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
exports.deepEqual = function deepEqual (a, b) { | |
if (a === b) return true; | |
if (a instanceof Date && b instanceof Date) | |
return a.getTime() === b.getTime(); | |
if (a instanceof ObjectId && b instanceof ObjectId) { | |
return a.toString() === b.toString(); | |
} | |
if (a instanceof RegExp && b instanceof RegExp) { | |
return a.source == b.source && | |
a.ignoreCase == b.ignoreCase && | |
a.multiline == b.multiline && | |
a.global == b.global; | |
} | |
if (typeof a !== 'object' && typeof b !== 'object') | |
return a == b; | |
if (a === null || b === null || a === undefined || b === undefined) | |
return false | |
if (a.prototype !== b.prototype) return false; | |
// Handle MongooseNumbers | |
if (a instanceof Number && b instanceof Number) { | |
return a.valueOf() === b.valueOf(); | |
} | |
if (Buffer.isBuffer(a)) { | |
return exports.buffer.areEqual(a, b); | |
} | |
if (isMongooseObject(a)) a = a.toObject(); | |
if (isMongooseObject(b)) b = b.toObject(); | |
try { | |
var ka = Object.keys(a), | |
kb = Object.keys(b), | |
key, i; | |
} catch (e) {//happens when one is a string literal and the other isn't | |
return false; | |
} | |
// having the same number of owned properties (keys incorporates | |
// hasOwnProperty) | |
if (ka.length != kb.length) | |
return false; | |
//the same set of keys (although not necessarily the same order), | |
ka.sort(); | |
kb.sort(); | |
//~~~cheap key test | |
for (i = ka.length - 1; i >= 0; i--) { | |
if (ka[i] != kb[i]) | |
return false; | |
} | |
//equivalent values for every corresponding key, and | |
//~~~possibly expensive deep test | |
for (i = ka.length - 1; i >= 0; i--) { | |
key = ka[i]; | |
if (!deepEqual(a[key], b[key])) return false; | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment