Merge pull request #1206 from brandonbloom/apply

$apply directive for update
This commit is contained in:
Cheng Lou 2014-06-12 20:34:29 -07:00
commit 3eb36415bd
2 changed files with 23 additions and 3 deletions

View File

@ -78,6 +78,14 @@ describe('update', function() {
expect(update({a: 'b'}, {$set: {c: 'd'}})).toEqual({c: 'd'});
});
it('should support apply', function() {
expect(update(2, {$apply: function(x) { return x * 2; }})).toEqual(4);
expect(update.bind(null, 2, {$apply: 123})).toThrow(
'Invariant Violation: update(): expected spec of $apply to be a ' +
'function; got 123.'
);
});
it('should support deep updates', function() {
expect(update({a: 'b', c: {d: 'e'}}, {c: {d: {$set: 'f'}}})).toEqual({
a: 'b',
@ -88,8 +96,8 @@ describe('update', function() {
it('should require a command', 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. ' +
'Did you forget to include {$set: ...}?'
'that did not contain one of $push, $unshift, $splice, $set, $merge, ' +
'$apply. Did you forget to include {$set: ...}?'
);
});
});

View File

@ -37,13 +37,15 @@ var COMMAND_UNSHIFT = keyOf({$unshift: null});
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 ALL_COMMANDS_LIST = [
COMMAND_PUSH,
COMMAND_UNSHIFT,
COMMAND_SPLICE,
COMMAND_SET,
COMMAND_MERGE
COMMAND_MERGE,
COMMAND_APPLY
];
var ALL_COMMANDS_SET = {};
@ -147,6 +149,16 @@ function update(value, spec) {
});
}
if (spec.hasOwnProperty(COMMAND_APPLY)) {
invariant(
typeof spec[COMMAND_APPLY] === 'function',
'update(): expected spec of %s to be a function; got %s.',
COMMAND_APPLY,
spec[COMMAND_APPLY]
);
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);