core/convert.js

  1. import { apply } from 'path/apply'
  2. const makeOperation = updater => (obj, prop, value, ...args) => { obj[prop] = updater(value, ...args) }
  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. * @memberof core
  8. * @param {function} updater The updater function.
  9. * @return {function} Returns the wrapped function.
  10. * @example <caption>Wrapping an updater</caption>
  11. * const inc = (v, i = 1) => v + i // this function increments a number with an optional value which defaults to 1
  12. * const incProp = convert(inc)
  13. * const object = { nested: { prop: 4 } }
  14. * incProp(object, 'nested.prop') // => { nested: { prop: 5 } }
  15. * incProp(object, 'nested.prop', 2) // => { nested: { prop: 6 } }
  16. * @see {@link core.update|update} for more information.
  17. * @since 1.0.0
  18. */
  19. const convert = updater => apply(makeOperation(updater))
  20. export { convert }