Last active
May 23, 2017 19:02
-
-
Save dounan/508e42a5aed79ce1f843504f97118e6a to your computer and use it in GitHub Desktop.
objShallowEqual.js
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
// OWNERS: dounan | |
// @flow | |
/** | |
* Shallow equality comparison of the object values | |
* @param {Object} objA - Source object | |
* @param {Object} objB - Object to compare to | |
* @param {Function} customizer - Custom equality comparison. Return undefined | |
* to use the default comparator. | |
* @return {Boolean} true iff objA and objB are shallowly equal | |
*/ | |
export default function(objA: ?{}, objB: ?{}, customizer?: Customizer): boolean { | |
if (objA === objB) { | |
return true; | |
} | |
if (!objA || !objB) { | |
return false; | |
} | |
const keysA = Object.keys(objA); | |
const keysB = Object.keys(objB); | |
if (keysA.length !== keysB.length) { | |
return false; | |
} | |
const inObjB = Object.prototype.hasOwnProperty.bind(objB); | |
for (let i = 0, n = keysA.length; i < n; i++) { | |
const k = keysA[i]; | |
if (!inObjB(k)) { | |
const a = objA[k]; | |
const b = objB[k]; | |
let result; | |
if (customizer) { | |
result = customizer(a, b, k); | |
} | |
result = result === undefined ? a === b : result; | |
if (!result) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
export type Customizer = (a: mixed, b: mixed, key: string) => boolean; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment