Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#2325 : Add $inc support for Helpers update #2352

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/addons/__tests__/update-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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: ...}?'
);
});
});
23 changes: 22 additions & 1 deletion src/addons/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ 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,
COMMAND_UNSHIFT,
COMMAND_SPLICE,
COMMAND_SET,
COMMAND_MERGE,
COMMAND_APPLY
COMMAND_APPLY,
COMMAND_INC
];

var ALL_COMMANDS_SET = {};
Expand Down Expand Up @@ -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]);
Expand Down