Ramda Adjunct 2.33.0

viewOr.js

  1. import { view, defaultTo, curryN } from 'ramda';
  2. /**
  3. * Returns a "view" of the given data structure, determined by the given lens.
  4. * The lens's focus determines which portion of the data structure is visible.
  5. * Returns the defaultValue if "view" is null, undefined or NaN; otherwise the "view" is returned.
  6. *
  7. * @func viewOr
  8. * @memberOf RA
  9. * @since {@link https://char0n.github.io/ramda-adjunct/1.13.0|1.13.0}
  10. * @category Object
  11. * @typedef Lens s b = Functor f => (b -> f b) -> s -> f s
  12. * @sig a -> Lens s b -> s -> b | a
  13. * @see {@link http://ramdajs.com/docs/#view|R.view}
  14. * @param {*} defaultValue The default value
  15. * @param {Function} lens Van Laarhoven lens
  16. * @param {*} data The data structure
  17. * @returns {*} "view" or defaultValue
  18. *
  19. * @example
  20. *
  21. * RA.viewOr('N/A', R.lensProp('x'), {}); // => 'N/A'
  22. * RA.viewOr('N/A', R.lensProp('x'), { x: 1 }); // => 1
  23. * RA.viewOr('some', R.lensProp('y'), { y: null }); // => 'some'
  24. * RA.viewOr('some', R.lensProp('y'), { y: false }); // => false
  25. */
  26. const viewOr = curryN(3, (defaultValue, lens, data) =>
  27. defaultTo(defaultValue, view(lens, data))
  28. );
  29. export default viewOr;