Skip to content

Instantly share code, notes, and snippets.

@elyobo
Created June 12, 2021 00:28
Show Gist options
  • Save elyobo/934f6896788236670ec4367c89a79412 to your computer and use it in GitHub Desktop.
Save elyobo/934f6896788236670ec4367c89a79412 to your computer and use it in GitHub Desktop.
Extract of React's `shallowCompare`
/**
* Extracted React shallowEqual, because it's not exported.
*
* @see https://github.com/facebook/react/issues/16919
* @see https://github.com/facebook/react/blob/master/packages/shared/shallowEqual.js
*/
const hasOwnProperty = Object.prototype.hasOwnProperty
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
const is = (x, y) => (
(x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare
)
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
const shallowEqual = (objA, objB) => {
if (is(objA, objB)) return true
if (
typeof objA !== 'object'
|| objA === null
|| typeof objB !== 'object'
|| objB === null
) {
return false
}
const keysA = Object.keys(objA)
const keysB = Object.keys(objB)
if (keysA.length !== keysB.length) return false
// Test for A's keys different from B.
for (let i = 0; i < keysA.length; i++) {
if (
!hasOwnProperty.call(objB, keysA[i])
|| !is(objA[keysA[i]], objB[keysA[i]])
) {
return false
}
}
return true
}
export default shallowEqual
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment