You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.0 KiB

4 years ago
  1. import _curry2 from "./internal/_curry2.js";
  2. import _dispatchable from "./internal/_dispatchable.js";
  3. import _map from "./internal/_map.js";
  4. import _reduce from "./internal/_reduce.js";
  5. import _xmap from "./internal/_xmap.js";
  6. import curryN from "./curryN.js";
  7. import keys from "./keys.js";
  8. /**
  9. * Takes a function and
  10. * a [functor](https://github.com/fantasyland/fantasy-land#functor),
  11. * applies the function to each of the functor's values, and returns
  12. * a functor of the same shape.
  13. *
  14. * Ramda provides suitable `map` implementations for `Array` and `Object`,
  15. * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`.
  16. *
  17. * Dispatches to the `map` method of the second argument, if present.
  18. *
  19. * Acts as a transducer if a transformer is given in list position.
  20. *
  21. * Also treats functions as functors and will compose them together.
  22. *
  23. * @func
  24. * @memberOf R
  25. * @since v0.1.0
  26. * @category List
  27. * @sig Functor f => (a -> b) -> f a -> f b
  28. * @param {Function} fn The function to be called on every element of the input `list`.
  29. * @param {Array} list The list to be iterated over.
  30. * @return {Array} The new list.
  31. * @see R.transduce, R.addIndex
  32. * @example
  33. *
  34. * const double = x => x * 2;
  35. *
  36. * R.map(double, [1, 2, 3]); //=> [2, 4, 6]
  37. *
  38. * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}
  39. * @symb R.map(f, [a, b]) = [f(a), f(b)]
  40. * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) }
  41. * @symb R.map(f, functor_o) = functor_o.map(f)
  42. */
  43. var map =
  44. /*#__PURE__*/
  45. _curry2(
  46. /*#__PURE__*/
  47. _dispatchable(['fantasy-land/map', 'map'], _xmap, function map(fn, functor) {
  48. switch (Object.prototype.toString.call(functor)) {
  49. case '[object Function]':
  50. return curryN(functor.length, function () {
  51. return fn.call(this, functor.apply(this, arguments));
  52. });
  53. case '[object Object]':
  54. return _reduce(function (acc, key) {
  55. acc[key] = fn(functor[key]);
  56. return acc;
  57. }, {}, keys(functor));
  58. default:
  59. return _map(fn, functor);
  60. }
  61. }));
  62. export default map;