util/convert.js

  1. import lodashFpConvert from './lodashFpConvert'
  2. import update from '../object/update'
  3. /**
  4. * Wraps an <code>updater</code> function, returning a new function taking <code>object</code>, <code>path</code> and <code>…args</code> as parameters.<br/>
  5. * The <code>updater</code> function 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 util
  9. * @param {function} updater The updater function.
  10. * @return {function} Returns the wrapped function.
  11. * @example <caption>Wrapping an updater</caption>
  12. * const inc = (v, i = 1) => v + i // this function increments a number with an optional value which defaults to 1
  13. * const incProp = convert(inc)
  14. * const object = { nested: { prop: 4 } }
  15. * incProp(object, 'nested.prop') // => { nested: { prop: 5 } }
  16. * incProp(object, 'nested.prop', 2) // => { nested: { prop: 6 } }
  17. * @see {@link object.update|update} for more information.
  18. * @since 0.2.0
  19. */
  20. const convert = updater => (obj, path, ...rest) => update(obj, path, updater, ...rest)
  21. export default convert
  22. /**
  23. * Converts and wraps a lodash/fp function.
  24. * @function
  25. * @memberof util
  26. * @param {function} fn The lodash/fp function.
  27. * @return {function} Returns the wrapped function.
  28. * @see {@link util.convert|convert} for more information.
  29. * @since 0.2.0
  30. * @private
  31. */
  32. export const convertLodashFp = fn => convert(lodashFpConvert(fn))