UNPKG

1.65 kBJavaScriptView Raw
1import _arity from "./internal/_arity.js";
2import _curry1 from "./internal/_curry1.js";
3import map from "./map.js";
4import max from "./max.js";
5import 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
34var cond =
35/*#__PURE__*/
36_curry1(function cond(pairs) {
37 var arity = reduce(max, 0, map(function (pair) {
38 return pair[0].length;
39 }, pairs));
40 return _arity(arity, function () {
41 var idx = 0;
42
43 while (idx < pairs.length) {
44 if (pairs[idx][0].apply(this, arguments)) {
45 return pairs[idx][1].apply(this, arguments);
46 }
47
48 idx += 1;
49 }
50 });
51});
52
53export default cond;
\No newline at end of file