when/unless
Explore how to apply Ramda's when and unless functions for conditional execution based on predicates. Learn to write point-free functions that run only when conditions are met, using these tools to create cleaner, more readable conditional logic in functional programming.
We'll cover the following...
We'll cover the following...
Sometimes you only need the if statement, and the else simply returns the value unchanged.
Again, ternaries can work well here.
But we can also use the when function. It takes three arguments
- Predicate (function that returns
trueorfalse) - Function to run if predicate returns true
- The value to use
We can make it point-free.
Conveniently enough, Ramda lets you express the opposite logic using unless.
This runs your function if the predicate returns false.
Now this function only doubles odd numbers. If we wanted doubleIfEven, our predicate must flip as well.