chain.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import _curry2 from "./internal/_curry2.js";
  2. import _dispatchable from "./internal/_dispatchable.js";
  3. import _makeFlat from "./internal/_makeFlat.js";
  4. import _xchain from "./internal/_xchain.js";
  5. import map from "./map.js";
  6. /**
  7. * `chain` maps a function over a list and concatenates the results. `chain`
  8. * is also known as `flatMap` in some libraries.
  9. *
  10. * Dispatches to the `chain` method of the second argument, if present,
  11. * according to the [FantasyLand Chain spec](https://github.com/fantasyland/fantasy-land#chain).
  12. *
  13. * If second argument is a function, `chain(f, g)(x)` is equivalent to `f(g(x), x)`.
  14. *
  15. * Acts as a transducer if a transformer is given in list position.
  16. *
  17. * @func
  18. * @memberOf R
  19. * @since v0.3.0
  20. * @category List
  21. * @sig Chain m => (a -> m b) -> m a -> m b
  22. * @param {Function} fn The function to map with
  23. * @param {Array} list The list to map over
  24. * @return {Array} The result of flat-mapping `list` with `fn`
  25. * @example
  26. *
  27. * const duplicate = n => [n, n];
  28. * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
  29. *
  30. * R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]
  31. */
  32. var chain =
  33. /*#__PURE__*/
  34. _curry2(
  35. /*#__PURE__*/
  36. _dispatchable(['fantasy-land/chain', 'chain'], _xchain, function chain(fn, monad) {
  37. if (typeof monad === 'function') {
  38. return function (x) {
  39. return fn(monad(x))(x);
  40. };
  41. }
  42. return _makeFlat(false)(map(fn, monad));
  43. }));
  44. export default chain;