shallowEqual: bail if either argument is falsey
Also add some unit tests.
Ian Obermiller committed
Mar 4, 2015 at 22:16 UTC
34f4a0e42da6831dc4cdc5d9e7728acc99582363
2 files changed
+76
src/utils/__tests__/shallowEqual-test.js
new
+71
@@ -0,0 +1,71 @@
1
+/**
2
+ * Copyright 2014-2015, 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
+ * @emails react-core
10
+ */
11
+
12
+'use strict';
13
+
14
+require('mock-modules')
15
+ .dontMock('shallowEqual');
16
+
17
+var shallowEqual;
18
+
19
+describe('shallowEqual', function() {
20
+
21
+ beforeEach(function() {
22
+ shallowEqual = require('shallowEqual');
23
+ });
24
+
25
+ it('returns false if either argument is null', function() {
26
+ expect(shallowEqual(null, {})).toBe(false);
27
+ expect(shallowEqual({}, null)).toBe(false);
28
+ });
29
+
30
+ it('returns true if both arguments are null or undefined', function() {
31
+ expect(shallowEqual(null, null)).toBe(true);
32
+ expect(shallowEqual(undefined, undefined)).toBe(true);
33
+ });
34
+
35
+ it('returns true if arguments are shallow equal', function() {
36
+ expect(
37
+ shallowEqual(
38
+ {a: 1, b: 2, c: 3},
39
+ {a: 1, b: 2, c: 3}
40
+ )
41
+ ).toBe(true);
42
+ });
43
+
44
+ it('returns false if first argument has too many keys', function() {
45
+ expect(
46
+ shallowEqual(
47
+ {a: 1, b: 2, c: 3},
48
+ {a: 1, b: 2}
49
+ )
50
+ ).toBe(false);
51
+ });
52
+
53
+ it('returns false if second argument has too many keys', function() {
54
+ expect(
55
+ shallowEqual(
56
+ {a: 1, b: 2},
57
+ {a: 1, b: 2, c: 3}
58
+ )
59
+ ).toBe(false);
60
+ });
61
+
62
+ it('returns false if arguments are not shallow equal', function() {
63
+ expect(
64
+ shallowEqual(
65
+ {a: 1, b: 2, c: {}},
66
+ {a: 1, b: 2, c: {}}
67
+ )
68
+ ).toBe(false);
69
+ });
70
+
71
+});
src/utils/shallowEqual.js
+5
@@ -22,6 +22,11 @@ function shallowEqual(objA, objB) {
22
if (objA === objB) {
23
return true;
24
}
25
+
26
+ if (!objA || !objB) {
27
+ return false;
28
+ }
29
+
30
var key;
31
// Test for A's keys different from B.
32
for (key in objA) {