$apply command for update
Brandon Bloom committed
Mar 2, 2014 at 00:01 UTC
86161c9c483a9664c0c39218de10d7e17efd653e
2 files changed
+23
-3
src/addons/__tests__/update-test.js
+10
-2
@@ -78,6 +78,14 @@ describe('update', function() {
78
expect(update({a: 'b'}, {$set: {c: 'd'}})).toEqual({c: 'd'});
79
});
80
81
+ it('should support apply', function() {
82
+ expect(update(2, {$apply: function(x) { return x * 2; }})).toEqual(4);
83
+ expect(update.bind(null, 2, {$apply: 123})).toThrow(
84
+ 'Invariant Violation: update(): expected spec of $apply to be a ' +
85
+ 'function; got 123.'
86
+ );
87
+ });
88
+
89
it('should support deep updates', function() {
90
expect(update({a: 'b', c: {d: 'e'}}, {c: {d: {$set: 'f'}}})).toEqual({
91
a: 'b',
@@ -88,8 +96,8 @@ describe('update', function() {
96
it('should require a command', function() {
97
expect(update.bind(null, {a: 'b'}, {a: 'c'})).toThrow(
98
'Invariant Violation: update(): You provided a key path to update() ' +
91
- 'that did not contain one of $push, $unshift, $splice, $set, $merge. ' +
92
- 'Did you forget to include {$set: ...}?'
99
+ 'that did not contain one of $push, $unshift, $splice, $set, $merge, ' +
100
+ '$apply. Did you forget to include {$set: ...}?'
101
);
102
});
103
});
src/addons/update.js
+13
-1
@@ -37,13 +37,15 @@ var COMMAND_UNSHIFT = keyOf({$unshift: null});
37
var COMMAND_SPLICE = keyOf({$splice: null});
38
var COMMAND_SET = keyOf({$set: null});
39
var COMMAND_MERGE = keyOf({$merge: null});
40
+var COMMAND_APPLY = keyOf({$apply: null});
41
42
var ALL_COMMANDS_LIST = [
43
COMMAND_PUSH,
44
COMMAND_UNSHIFT,
45
COMMAND_SPLICE,
46
COMMAND_SET,
46
- COMMAND_MERGE
47
+ COMMAND_MERGE,
48
+ COMMAND_APPLY
49
];
50
51
var ALL_COMMANDS_SET = {};
@@ -147,6 +149,16 @@ function update(value, spec) {
149
});
150
}
151
152
+ if (spec.hasOwnProperty(COMMAND_APPLY)) {
153
+ invariant(
154
+ typeof spec[COMMAND_APPLY] === 'function',
155
+ 'update(): expected spec of %s to be a function; got %s.',
156
+ COMMAND_APPLY,
157
+ spec[COMMAND_APPLY]
158
+ );
159
+ nextValue = spec[COMMAND_APPLY](nextValue);
160
+ }
161
+
162
for (var k in spec) {
163
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
164
nextValue[k] = update(value[k], spec[k]);