Functional programming with Ramda [cond]

Grigor Oganesyan
2 min readOct 26, 2022

--

For those who feel comfort and safety using imperative paradigm but already experienced beauty and elegance of functional programming I want to help with a series of articles which are supposed to explain when, how and why!

I talk about Ramda because of its functional nature, just the same set of tools should be available within Lodash, yet with Ramda you always 100% sure it’s exclusively functional.

I want to start right away with a practical and useful tool — Ramda.cond().

It is terrifying!

If you open official documentation https://ramdajs.com/docs/#cond you’ll find quite short explanation with an example. But just take a look at those predicate, transformer, equals, T, always brrrrr… Gooseflesh!

const 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'

We can handle it.

I’ll try simplify the example for us - normal developers:

const fn = R.cond([
[temp => temp === 0, () => 'water freezes at 0°C'],
[temp => temp === 100, () => 'water boils at 100°C'],
[() => true, 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 hope it looks much easier to understand. Basically it expects an array of if’s, and each element is another array, where first parameter plays a role of condition and the second is statement body - the code you want to execute when the condition is truthy. Now you might already see what it looks like the most… You are right! It’s a switch/case/if/else if/else killer.

That might make sense to consider using Ramda.cond() the next time you need to write something like that:

function whatHappensToWater(temp) {
let tellPeople = ''
if(temp === 100) {
tellPeople = 'water boils at 100°C'
} else if (temp === 0) {
tellPeople = 'water freezes at 0°C'
} else {
tellPeople = 'nothing special happens at ' + temp + '°C'
}
return tellPeople
}
whatHappensToWater(0)
whatHappensToWater(50)
whatHappensToWater(100)

Why?

The general idea is quite simple — whenever you have a number of conditional statements, especially if there are variables and they are being mutated (don’t tell anyone you mutate variables - it’s totally forbidden), remember that Ramda.cond() can make this code cleaner and smarter.

It’s going to be easy once you used to it.

--

--

Grigor Oganesyan

I’m a software developer with over a decade of experience. Here, I write about things that fascinate me with aim to help others on their tech journeys.