sequence.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import _curry2 from "./internal/_curry2.js";
  2. import ap from "./ap.js";
  3. import map from "./map.js";
  4. import prepend from "./prepend.js";
  5. import reduceRight from "./reduceRight.js";
  6. import identity from "./internal/_identity.js";
  7. /**
  8. * Transforms a [Traversable](https://github.com/fantasyland/fantasy-land#traversable)
  9. * of [Applicative](https://github.com/fantasyland/fantasy-land#applicative) into an
  10. * Applicative of Traversable.
  11. *
  12. * Dispatches to the `"fantasy-land/traverse"` or the `traverse` method of the second argument, if present.
  13. *
  14. * @func
  15. * @memberOf R
  16. * @since v0.19.0
  17. * @category List
  18. * @sig fantasy-land/of :: TypeRep f => f ~> a -> f a
  19. * @sig (Applicative f, Traversable t) => TypeRep f -> t (f a) -> f (t a)
  20. * @sig (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a)
  21. * @param {Object|Function} TypeRepresentative with an `of` or `fantasy-land/of` method
  22. * @param {*} traversable
  23. * @return {*}
  24. * @see R.traverse
  25. * @example
  26. *
  27. * R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3])
  28. * R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
  29. *
  30. * R.sequence(R.of(Array), Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)]
  31. * R.sequence(R.of(Array), Nothing()); //=> [Nothing()]
  32. */
  33. var sequence =
  34. /*#__PURE__*/
  35. _curry2(function sequence(F, traversable) {
  36. var of = typeof F['fantasy-land/of'] === 'function' ? F['fantasy-land/of'] : typeof F.of === 'function' ? F.of : F;
  37. var TypeRep = {
  38. 'fantasy-land/of': of
  39. };
  40. return typeof traversable['fantasy-land/traverse'] === 'function' ? traversable['fantasy-land/traverse'](TypeRep, identity) : typeof traversable.traverse === 'function' ? traversable.traverse(TypeRep, identity) : reduceRight(function (x, acc) {
  41. return ap(map(prepend, x), acc);
  42. }, of([]), traversable);
  43. });
  44. export default sequence;