main
js 54 lines 1.23 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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 * @flow
8 */
9
10 import is from './objectIs';
11 import hasOwnProperty from './hasOwnProperty';
12
13 /**
14 * Performs equality by iterating through keys on an object and returning false
15 * when any key has values which are not strictly equal between the arguments.
16 * Returns true when the values of all keys are strictly equal.
17 */
18 function shallowEqual(objA: mixed, objB: mixed): boolean {
19 if (is(objA, objB)) {
20 return true;
21 }
22
23 if (
24 typeof objA !== 'object' ||
25 objA === null ||
26 typeof objB !== 'object' ||
27 objB === null
28 ) {
29 return false;
30 }
31
32 const keysA = Object.keys(objA);
33 const keysB = Object.keys(objB);
34
35 if (keysA.length !== keysB.length) {
36 return false;
37 }
38
39 // Test for A's keys different from B.
40 for (let i = 0; i < keysA.length; i++) {
41 const currentKey = keysA[i];
42 if (
43 !hasOwnProperty.call(objB, currentKey) ||
44 // $FlowFixMe[incompatible-use] lost refinement of `objB`
45 !is(objA[currentKey], objB[currentKey])
46 ) {
47 return false;
48 }
49 }
50
51 return true;
52 }
53
54 export default shallowEqual;