traverse.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _curry3 from "./internal/_curry3.js";
  2. import map from "./map.js";
  3. import sequence from "./sequence.js";
  4. /**
  5. * Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning
  6. * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable),
  7. * then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative
  8. * into an Applicative of Traversable.
  9. *
  10. * Dispatches to the `traverse` method of the third argument, if present.
  11. *
  12. * @func
  13. * @memberOf R
  14. * @since v0.19.0
  15. * @category List
  16. * @sig fantasy-land/of :: TypeRep f => f ~> a -> f a
  17. * @sig (Applicative f, Traversable t) => TypeRep f -> (a -> f b) -> t a -> f (t b)
  18. * @sig (Applicative f, Traversable t) => (b -> f b) -> (a -> f b) -> t a -> f (t b)
  19. * @param {Object|Function} TypeRepresentative with an `of` or `fantasy-land/of` method
  20. * @param {Function} f
  21. * @param {*} traversable
  22. * @return {*}
  23. * @see R.sequence
  24. * @example
  25. *
  26. * // Returns `Maybe.Nothing` if the given divisor is `0`
  27. * const safeDiv = n => d => d === 0 ? Maybe.Nothing() : Maybe.Just(n / d)
  28. *
  29. * R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Maybe.Just([5, 2.5, 2])
  30. * R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Maybe.Nothing
  31. *
  32. * // Using a Type Representative
  33. * R.traverse(Maybe, safeDiv(10), Right(4)); //=> Just(Right(2.5))
  34. * R.traverse(Maybe, safeDiv(10), Right(0)); //=> Nothing
  35. * R.traverse(Maybe, safeDiv(10), Left("X")); //=> Just(Left("X"))
  36. */
  37. var traverse =
  38. /*#__PURE__*/
  39. _curry3(function traverse(F, f, traversable) {
  40. var of = typeof F['fantasy-land/of'] === 'function' ? F['fantasy-land/of'] : typeof F.of === 'function' ? F.of : F;
  41. var TypeRep = {
  42. 'fantasy-land/of': of
  43. };
  44. return typeof traversable['fantasy-land/traverse'] === 'function' ? traversable['fantasy-land/traverse'](TypeRep, f) : typeof traversable.traverse === 'function' ? traversable.traverse(TypeRep, f) : sequence(TypeRep, map(f, traversable));
  45. });
  46. export default traverse;