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