Skip to content

Commit 86161c9

Browse files
committed
$apply command for update
1 parent 927eb57 commit 86161c9

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/addons/__tests__/update-test.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,14 @@ describe('update', function() {
7878
expect(update({a: 'b'}, {$set: {c: 'd'}})).toEqual({c: 'd'});
7979
});
8080

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+
8189
it('should support deep updates', function() {
8290
expect(update({a: 'b', c: {d: 'e'}}, {c: {d: {$set: 'f'}}})).toEqual({
8391
a: 'b',
@@ -88,8 +96,8 @@ describe('update', function() {
8896
it('should require a command', function() {
8997
expect(update.bind(null, {a: 'b'}, {a: 'c'})).toThrow(
9098
'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: ...}?'
93101
);
94102
});
95103
});

src/addons/update.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,15 @@ var COMMAND_UNSHIFT = keyOf({$unshift: null});
3737
var COMMAND_SPLICE = keyOf({$splice: null});
3838
var COMMAND_SET = keyOf({$set: null});
3939
var COMMAND_MERGE = keyOf({$merge: null});
40+
var COMMAND_APPLY = keyOf({$apply: null});
4041

4142
var ALL_COMMANDS_LIST = [
4243
COMMAND_PUSH,
4344
COMMAND_UNSHIFT,
4445
COMMAND_SPLICE,
4546
COMMAND_SET,
46-
COMMAND_MERGE
47+
COMMAND_MERGE,
48+
COMMAND_APPLY
4749
];
4850

4951
var ALL_COMMANDS_SET = {};
@@ -147,6 +149,16 @@ function update(value, spec) {
147149
});
148150
}
149151

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+
150162
for (var k in spec) {
151163
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
152164
nextValue[k] = update(value[k], spec[k]);

0 commit comments

Comments
 (0)