object/update.js

  1. import _update from 'lodash/fp/update'
  2. import lodashFpConvert from '../util/lodashFpConvert'
  3. const convertedUpdate = lodashFpConvert(_update)
  4. /**
  5. * Updates the value at <code>path</code> of <code>object</code> using the <code>updater</code> function.<br/>
  6. * The updater is invoked with <code>value</code> and <code>…args</code>.<br/>
  7. * Be carefull, the <code>updater</code> function must not mutate its <code>value</code> argument.
  8. * @function
  9. * @memberof object
  10. * @param {Object} object The object to modify.
  11. * @param {Array|string} path The path of the property to set.
  12. * @param {function} updater The function to produce the updated value.
  13. * @param {...*} args The remaining args.
  14. * @return {Object} Returns the updated object.
  15. * @example <caption>Updating a prop</caption>
  16. * const inc = (v, i = 1) => v + i // this function increments a number with an optional value which defaults to 1
  17. * const object = { nested: { prop: 4 } }
  18. * update(object, 'nested.prop', inc) // => { nested: { prop: 5 } }
  19. * update(object, 'nested.prop', inc, 2) // => { nested: { prop: 6 } }
  20. * @see {@link https://lodash.com/docs#update|lodash.update} for more information.
  21. * @since 0.1.5
  22. */
  23. const update = (object, path, updater, ...args) => convertedUpdate(object, path, v => updater(v, ...args))
  24. export default update