Himmel Himmel - 3 years ago 181
Javascript Question

Ramda `cond` else statement

I'm looking at the Ramda docs for the

function and am confused about its behavior. The docs state that

Returns a function, fn, which encapsulates if/else-if/else logic.
R.cond takes a list of [predicate, transform] pairs. All of the
arguments to fn are applied to each of the predicates in turn until
one returns a "truthy" value, at which point fn returns the result of
applying its arguments to the corresponding transformer. If none of
the predicates matches, fn returns undefined.

Here is the example given:

var fn = R.cond([
[R.equals(0), R.always('water freezes at 0°C')],
[R.equals(100), R.always('water boils at 100°C')],
[R.T, temp => 'nothing special happens at ' + temp + '°C']

fn(0); //=> 'water freezes at 0°C'
fn(50); //=> 'nothing special happens at 50°C'
fn(100); //=> 'water boils at 100°C'

I understand the
[predicate, transform]
aspect of the function, but it isn't clear to me how the "else" portion works. In a typical if/else-if/else statement, the "else" portion does not accept a predicate. In the example, however, each of the arrays have a predicate. Maybe knowing how
operates in this case would help, but searching for
in the docs was fruitless.

How can I use Ramda's
function to capture conditional "else" functionality in order to return a default value?

Answer Source

R.T always returns true and ignores any parameters passed to it. That is the reason the 100 you passed in was ignored and it just returned true.

R.cond searches each of the [predicate, transform] pairs, and stops searching on the first predicate that evaluates to true. So the first matching entity from the [predicate, transform] pair would be evaluated.

If nothing is true, then it reaches the end and executes the R.T predicate (which is always true) and that acts like the else part of list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download