shallowEqual.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. * @typechecks
  8. *
  9. */
  10. /*eslint-disable no-self-compare */
  11. var hasOwnProperty = Object.prototype.hasOwnProperty;
  12. /**
  13. * inlined Object.is polyfill to avoid requiring consumers ship their own
  14. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  15. */
  16. function is(x, y) {
  17. // SameValue algorithm
  18. if (x === y) {
  19. // Steps 1-5, 7-10
  20. // Steps 6.b-6.e: +0 != -0
  21. // Added the nonzero y check to make Flow happy, but it is redundant
  22. return x !== 0 || y !== 0 || 1 / x === 1 / y;
  23. } else {
  24. // Step 6.a: NaN == NaN
  25. return x !== x && y !== y;
  26. }
  27. }
  28. /**
  29. * Performs equality by iterating through keys on an object and returning false
  30. * when any key has values which are not strictly equal between the arguments.
  31. * Returns true when the values of all keys are strictly equal.
  32. */
  33. function shallowEqual(objA, objB) {
  34. if (is(objA, objB)) {
  35. return true;
  36. }
  37. if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
  38. return false;
  39. }
  40. var keysA = Object.keys(objA);
  41. var keysB = Object.keys(objB);
  42. if (keysA.length !== keysB.length) {
  43. return false;
  44. }
  45. // Test for A's keys different from B.
  46. for (var i = 0; i < keysA.length; i++) {
  47. if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. export default shallowEqual