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.

52 lines
1.6 KiB

4 years ago
  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. * @func
  15. * @memberOf R
  16. * @since v0.6.0
  17. * @category Logic
  18. * @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
  19. * @param {Array} pairs A list of [predicate, transformer]
  20. * @return {Function}
  21. * @see R.ifElse, R.unless, R.when
  22. * @example
  23. *
  24. * const fn = R.cond([
  25. * [R.equals(0), R.always('water freezes at 0°C')],
  26. * [R.equals(100), R.always('water boils at 100°C')],
  27. * [R.T, temp => 'nothing special happens at ' + temp + '°C']
  28. * ]);
  29. * fn(0); //=> 'water freezes at 0°C'
  30. * fn(50); //=> 'nothing special happens at 50°C'
  31. * fn(100); //=> 'water boils at 100°C'
  32. */
  33. var cond =
  34. /*#__PURE__*/
  35. _curry1(function cond(pairs) {
  36. var arity = reduce(max, 0, map(function (pair) {
  37. return pair[0].length;
  38. }, pairs));
  39. return _arity(arity, function () {
  40. var idx = 0;
  41. while (idx < pairs.length) {
  42. if (pairs[idx][0].apply(this, arguments)) {
  43. return pairs[idx][1].apply(this, arguments);
  44. }
  45. idx += 1;
  46. }
  47. });
  48. });
  49. export default cond;