|
| 1 | +/** |
| 2 | + * Copyright (c) 2013-present, Facebook, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. An additional grant |
| 7 | + * of patent rights can be found in the PATENTS file in the same directory. |
| 8 | + * |
| 9 | + * @providesModule shallowEqual |
| 10 | + * @typechecks |
| 11 | + * @flow |
| 12 | + */ |
| 13 | + |
| 14 | +/*eslint-disable no-self-compare */ |
| 15 | + |
| 16 | +'use strict'; |
| 17 | + |
| 18 | +const hasOwnProperty = Object.prototype.hasOwnProperty; |
| 19 | + |
| 20 | +/** |
| 21 | + * inlined Object.is polyfill to avoid requiring consumers ship their own |
| 22 | + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is |
| 23 | + */ |
| 24 | +function is(x: mixed, y: mixed): boolean { |
| 25 | + // SameValue algorithm |
| 26 | + if (x === y) { |
| 27 | + // Steps 1-5, 7-10 |
| 28 | + // Steps 6.b-6.e: +0 != -0 |
| 29 | + // Added the nonzero y check to make Flow happy, but it is redundant |
| 30 | + return x !== 0 || y !== 0 || 1 / x === 1 / y; |
| 31 | + } else { |
| 32 | + // Step 6.a: NaN == NaN |
| 33 | + return x !== x && y !== y; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Performs equality by iterating through keys on an object and returning false |
| 39 | + * when any key has values which are not strictly equal between the arguments. |
| 40 | + * Returns true when the values of all keys are strictly equal. |
| 41 | + */ |
| 42 | +function shallowEqual(objA: mixed, objB: mixed): boolean { |
| 43 | + if (is(objA, objB)) { |
| 44 | + return true; |
| 45 | + } |
| 46 | + if ( |
| 47 | + typeof objA !== 'object' || |
| 48 | + objA === null || |
| 49 | + typeof objB !== 'object' || |
| 50 | + objB === null |
| 51 | + ) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + const keysA = Object.keys(objA); |
| 56 | + const keysB = Object.keys(objB); |
| 57 | + |
| 58 | + if (keysA.length !== keysB.length) { |
| 59 | + return false; |
| 60 | + } |
| 61 | + |
| 62 | + // Test for A's keys different from B. |
| 63 | + for (let i = 0; i < keysA.length; i++) { |
| 64 | + if ( |
| 65 | + !hasOwnProperty.call(objB, keysA[i]) || |
| 66 | + !is(objA[keysA[i]], objB[keysA[i]]) |
| 67 | + ) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return true; |
| 73 | +} |
| 74 | + |
| 75 | +module.exports = shallowEqual; |
0 commit comments