cond.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import _arity from "./internal/_arity.js";
  2. import _curry1 from "./internal/_curry1.js";
  3. import map from "./map.js";
  4. import max from "./max.js";
  5. import reduce from "./reduce.js";
  6. /**
  7. * Returns a function, `fn`, which encapsulates `if/else, if/else, ...` logic.
  8. * `R.cond` takes a list of [predicate, transformer] pairs. All of the arguments
  9. * to `fn` are applied to each of the predicates in turn until one returns a
  10. * "truthy" value, at which point `fn` returns the result of applying its
  11. * arguments to the corresponding transformer. If none of the predicates
  12. * matches, `fn` returns undefined.
  13. *
  14. * **Please note**: This is not a direct substitute for a `switch` statement.
  15. * Remember that both elements of every pair passed to `cond` are *functions*,
  16. * and `cond` returns a function.
  17. *
  18. * @func
  19. * @memberOf R
  20. * @since v0.6.0
  21. * @category Logic
  22. * @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
  23. * @param {Array} pairs A list of [predicate, transformer]
  24. * @return {Function}
  25. * @see R.ifElse, R.unless, R.when
  26. * @example
  27. *
  28. * const fn = R.cond([
  29. * [R.equals(0), R.always('water freezes at 0°C')],
  30. * [R.equals(100), R.always('water boils at 100°C')],
  31. * [R.T, temp => 'nothing special happens at ' + temp + '°C']
  32. * ]);
  33. * fn(0); //=> 'water freezes at 0°C'
  34. * fn(50); //=> 'nothing special happens at 50°C'
  35. * fn(100); //=> 'water boils at 100°C'
  36. */
  37. var cond =
  38. /*#__PURE__*/
  39. _curry1(function cond(pairs) {
  40. var arity = reduce(max, 0, map(function (pair) {
  41. return pair[0].length;
  42. }, pairs));
  43. return _arity(arity, function () {
  44. var idx = 0;
  45. while (idx < pairs.length) {
  46. if (pairs[idx][0].apply(this, arguments)) {
  47. return pairs[idx][1].apply(this, arguments);
  48. }
  49. idx += 1;
  50. }
  51. });
  52. });
  53. export default cond;