UNPKG

1.73 kBJavaScriptView Raw
1var _arity =
2/*#__PURE__*/
3require("./internal/_arity");
4
5var _curry1 =
6/*#__PURE__*/
7require("./internal/_curry1");
8
9var map =
10/*#__PURE__*/
11require("./map");
12
13var max =
14/*#__PURE__*/
15require("./max");
16
17var reduce =
18/*#__PURE__*/
19require("./reduce");
20/**
21 * Returns a function, `fn`, which encapsulates `if/else, if/else, ...` logic.
22 * `R.cond` takes a list of [predicate, transformer] pairs. All of the arguments
23 * to `fn` are applied to each of the predicates in turn until one returns a
24 * "truthy" value, at which point `fn` returns the result of applying its
25 * arguments to the corresponding transformer. If none of the predicates
26 * matches, `fn` returns undefined.
27 *
28 * @func
29 * @memberOf R
30 * @since v0.6.0
31 * @category Logic
32 * @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
33 * @param {Array} pairs A list of [predicate, transformer]
34 * @return {Function}
35 * @see R.ifElse, R.unless, R.when
36 * @example
37 *
38 * const fn = R.cond([
39 * [R.equals(0), R.always('water freezes at 0°C')],
40 * [R.equals(100), R.always('water boils at 100°C')],
41 * [R.T, temp => 'nothing special happens at ' + temp + '°C']
42 * ]);
43 * fn(0); //=> 'water freezes at 0°C'
44 * fn(50); //=> 'nothing special happens at 50°C'
45 * fn(100); //=> 'water boils at 100°C'
46 */
47
48
49var cond =
50/*#__PURE__*/
51_curry1(function cond(pairs) {
52 var arity = reduce(max, 0, map(function (pair) {
53 return pair[0].length;
54 }, pairs));
55 return _arity(arity, function () {
56 var idx = 0;
57
58 while (idx < pairs.length) {
59 if (pairs[idx][0].apply(this, arguments)) {
60 return pairs[idx][1].apply(this, arguments);
61 }
62
63 idx += 1;
64 }
65 });
66});
67
68module.exports = cond;
\No newline at end of file