lens.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import _curry2 from "./internal/_curry2.js";
  2. import map from "./map.js";
  3. /**
  4. * Returns a lens for the given getter and setter functions. The getter "gets"
  5. * the value of the focus; the setter "sets" the value of the focus. The setter
  6. * should not mutate the data structure.
  7. *
  8. * @func
  9. * @memberOf R
  10. * @since v0.8.0
  11. * @category Object
  12. * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
  13. * @sig (s -> a) -> ((a, s) -> s) -> Lens s a
  14. * @param {Function} getter
  15. * @param {Function} setter
  16. * @return {Lens}
  17. * @see R.view, R.set, R.over, R.lensIndex, R.lensProp
  18. * @example
  19. *
  20. * const xLens = R.lens(R.prop('x'), R.assoc('x'));
  21. *
  22. * R.view(xLens, {x: 1, y: 2}); //=> 1
  23. * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
  24. * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
  25. */
  26. var lens =
  27. /*#__PURE__*/
  28. _curry2(function lens(getter, setter) {
  29. return function (toFunctorFn) {
  30. return function (target) {
  31. return map(function (focus) {
  32. return setter(focus, target);
  33. }, toFunctorFn(getter(target)));
  34. };
  35. };
  36. });
  37. export default lens;