Use Object.assign in merge/mergeInto
Relax the argument type checks. Currently we throw for non-objects and terminals but Object.assign does a coercion to Object instead. It also allows merging Arrays as if they are objects. This also relaxes the check for dependents such as ImmutableObject. This sucks but it will allow us to use a fast code path to native Object.assign. We always have the option of adding warnings to Object.assign or static type checks. I'm keeping the null check. Object.assign throws for null checks. We'll also start returning the result of coercions just like Object.assign.
Sebastian Markbage committed
Jul 18, 2014 at 10:03 UTC
3818656f70d42232ab4b4c199107af0674a16e37
3 files changed
+16
-20
src/utils/__tests__/LegacyImmutableObject-test.js
+5
-3
@@ -75,14 +75,16 @@ describe('LegacyImmutableObject', function() {
75
expect(window.__DEV__).toBe(true);
76
});
77
78
- testDev('should require initial map to be an object', function() {
78
+ testDev('should not require initial map to be an object', function() {
79
+ // These won't throw because they're coerced
80
+
81
expect(function() {
82
new LegacyImmutableObject([1,2,3]);
81
- }).toThrow();
83
+ }).not.toThrow();
84
85
expect(function() {
86
new LegacyImmutableObject('asdf');
85
- }).toThrow();
87
+ }).not.toThrow();
88
89
expect(function() {
90
new LegacyImmutableObject({oldField: 'asdf', fieldTwo: null});
src/vendor/core/merge.js
+6
-4
@@ -18,8 +18,6 @@
18
19
"use strict";
20
21
-var mergeInto = require('mergeInto');
22
-
21
/**
22
* Shallow merges two structures into a return value, without mutating either.
23
*
@@ -29,8 +27,12 @@ var mergeInto = require('mergeInto');
27
*/
28
var merge = function(one, two) {
29
var result = {};
32
- mergeInto(result, one);
33
- mergeInto(result, two);
30
+ if (one != null) {
31
+ Object.assign(result, one);
32
+ }
33
+ if (two != null) {
34
+ Object.assign(result, two);
35
+ }
36
return result;
37
};
38
src/vendor/core/mergeInto.js
+5
-13
@@ -19,27 +19,19 @@
19
20
"use strict";
21
22
-var mergeHelpers = require('mergeHelpers');
23
-
24
-var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg;
25
-var checkMergeIntoObjectArg = mergeHelpers.checkMergeIntoObjectArg;
26
-
22
/**
23
* Shallow merges two structures by mutating the first parameter.
24
*
25
* @param {object|function} one Object to be merged into.
26
* @param {?object} two Optional object with properties to merge from.
27
+ * @return {object|function} The first argument coerced into an object.
28
*/
29
function mergeInto(one, two) {
34
- checkMergeIntoObjectArg(one);
30
if (two != null) {
36
- checkMergeObjectArg(two);
37
- for (var key in two) {
38
- if (!two.hasOwnProperty(key)) {
39
- continue;
40
- }
41
- one[key] = two[key];
42
- }
31
+ return Object.assign(one, two);
32
+ } else {
33
+ // This ensures that we throw the right error if one is of the wrong type
34
+ return Object.assign(one);
35
}
36
}
37