diff --git a/src/addons/__tests__/update-test.js b/src/addons/__tests__/update-test.js index 3c5dda77525..85fff41193f 100644 --- a/src/addons/__tests__/update-test.js +++ b/src/addons/__tests__/update-test.js @@ -79,6 +79,19 @@ describe('update', function() { ); }); + it('should support inc', function() { + expect(update(3, {$inc: 2})).toEqual(5); + + expect(update.bind(null, '3', {$inc: 3})).toThrow( + 'Invariant Violation: update(): Expected $inc target to be a number; got a string. ' + ); + + expect(update.bind(null, 3, {$inc: '5'})).toThrow( + 'Invariant Violation: update(): Expected spec of $inc to be a number; got a string. ' + ) + + }); + it('should support deep updates', function() { expect(update({a: 'b', c: {d: 'e'}}, {c: {d: {$set: 'f'}}})).toEqual({ a: 'b', @@ -90,7 +103,7 @@ describe('update', function() { expect(update.bind(null, {a: 'b'}, {a: 'c'})).toThrow( 'Invariant Violation: update(): You provided a key path to update() ' + 'that did not contain one of $push, $unshift, $splice, $set, $merge, ' + - '$apply. Did you forget to include {$set: ...}?' + '$apply, $inc. Did you forget to include {$set: ...}?' ); }); }); diff --git a/src/addons/update.js b/src/addons/update.js index dded114ea41..6c21c111b5c 100644 --- a/src/addons/update.js +++ b/src/addons/update.js @@ -30,6 +30,7 @@ var COMMAND_SPLICE = keyOf({$splice: null}); var COMMAND_SET = keyOf({$set: null}); var COMMAND_MERGE = keyOf({$merge: null}); var COMMAND_APPLY = keyOf({$apply: null}); +var COMMAND_INC = keyOf({$inc: null}); var ALL_COMMANDS_LIST = [ COMMAND_PUSH, @@ -37,7 +38,8 @@ var ALL_COMMANDS_LIST = [ COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, - COMMAND_APPLY + COMMAND_APPLY, + COMMAND_INC ]; var ALL_COMMANDS_SET = {}; @@ -151,6 +153,25 @@ function update(value, spec) { nextValue = spec[COMMAND_APPLY](nextValue); } + if (spec.hasOwnProperty(COMMAND_INC)) { + + invariant( + typeof value === "number", + 'update(): Expected %s target to be a number; got a %s. ', + COMMAND_INC, + typeof value + ); + + invariant( + typeof spec[COMMAND_INC] === "number", + 'update(): Expected spec of %s to be a number; got a %s. ', + COMMAND_INC, + typeof spec[COMMAND_INC] + ); + + nextValue += spec[COMMAND_INC]; + } + for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]);