function update(object, spec) {
invariant(
!Array.isArray(spec),
'update(): You provided an invalid spec to update(). The spec may ' +
'not contain an array except as the value of $set, $push, $unshift, ' +
'$splice or any custom command allowing an array value.'
);
invariant(
typeof spec === 'object' && spec !== null,
'update(): You provided an invalid spec to update(). The spec and ' +
'every included key path must be plain objects containing one of the ' +
'following commands: %s.',
Object.keys(commands).join(', ')
);
var nextObject = object;
var specKeys = getAllKeys(spec)
var index, key;
for (index = 0; index < specKeys.length; index++) {
var key = specKeys[index];
if (hasOwnProperty.call(commands, key)) {
nextObject = commands[key](spec[key], nextObject, spec, object);
} else {
var nextValueForKey = update(object[key], spec[key]);
if (nextValueForKey !== nextObject[key]) {
if (nextObject === object) {
nextObject = copy(object);
}
nextObject[key] = nextValueForKey;
}
}
}
return nextObject;
}n/a
extend = function (directive, fn) {
commands[directive] = fn;
}...
---
The main difference this module has with `react-addons-update` is that
you can extend this to give it more functionality:
```js
update.extend('$addtax', function(tax, original) {
return original + (tax * original);
});
const state = { price: 123 };
const withTax = update(state, {
price: {$addtax: 0.8},
});
assert(JSON.stringify(withTax) === JSON.stringify({ price: 221.4 });
...function newContext() {
var commands = assign({}, defaultCommands);
update.extend = function(directive, fn) {
commands[directive] = fn;
}
return update;
function update(object, spec) {
invariant(
!Array.isArray(spec),
'update(): You provided an invalid spec to update(). The spec may ' +
'not contain an array except as the value of $set, $push, $unshift, ' +
'$splice or any custom command allowing an array value.'
);
invariant(
typeof spec === 'object' && spec !== null,
'update(): You provided an invalid spec to update(). The spec and ' +
'every included key path must be plain objects containing one of the ' +
'following commands: %s.',
Object.keys(commands).join(', ')
);
var nextObject = object;
var specKeys = getAllKeys(spec)
var index, key;
for (index = 0; index < specKeys.length; index++) {
var key = specKeys[index];
if (hasOwnProperty.call(commands, key)) {
nextObject = commands[key](spec[key], nextObject, spec, object);
} else {
var nextValueForKey = update(object[key], spec[key]);
if (nextValueForKey !== nextObject[key]) {
if (nextObject === object) {
nextObject = copy(object);
}
nextObject[key] = nextValueForKey;
}
}
}
return nextObject;
}
}n/a