shallowEqual.js.flow 1.7 KB

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