core/update.js

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