core/update.js

  1. import { apply } from './apply'
  2. /**
  3. * Updates the value at <code>path</code> of <code>object</code> using the <code>updater</code> function.<br/>
  4. * The updater is invoked with <code>value</code> and <code>…args</code>.<br/>
  5. * Be carefull, the <code>updater</code> function must not mutate its <code>value</code> argument.
  6. * @function
  7. * @memberof core
  8. * @param {Object} obj The object to modify.
  9. * @param {Array|string} path The path of the property to set.
  10. * @param {function} updater The function to produce the updated value.
  11. * @param {...*} args The remaining args.
  12. * @return {Object} Returns the updated object.
  13. * @example <caption>Updating a prop</caption>
  14. * const inc = (v, i = 1) => v + i // this function increments a number with an optional value which defaults to 1
  15. * const object = { nested: { prop: 4 } }
  16. * update(object, 'nested.prop', inc) // => { nested: { prop: 5 } }
  17. * update(object, 'nested.prop', inc, 2) // => { nested: { prop: 6 } }
  18. * @since 1.0.0
  19. */
  20. const update = apply((value, fn, ...args) => fn(value, ...args))
  21. export { update }