A couple of times I have been asked “How would you do X in functional programming?” I absolutely love these types of questions.
I do my best to answer every question, but I think there are many questions interesting enough to warrant their own articles.
So for this article I would like to demonstrate how I could recreate this imperative function in a more functional manner.
This function has an
if statement without an
else. So while a
ternary operator could work, it is not ideal.
Here we need to run `dispatch` only when we have a `value`, otherwise we do nothing.
One option is to use a short circuit operator:
Short circuit and ternary and both ways you can solve this problem, but let’s take a look at a couple more.
To do this in a more functional way, I will create a helper function. I’ll write this helper old school first then boil it down piece by piece so everyone can understand it easily.
Now we can modify our
someAction function to use
ifVal instead of the classic
Here’s the comparison for a quick and easy twitter screenshot:
We could also use the Maybe Type. The Maybe Type consists of either a
Just type which holds a value or a
Nothing type which is exactly what is says.
For this example, I’ll use the Maybe Type from the Sanctuary library.
It looks a little like this:
The Maybe Type is pretty simple and the reason why I want to use it is because
Maybe work together so well, it was been given a special name, a Functor.
Some libraries like ramda-fantasy have a fluent syntax, but this article is using Sanctuary. Though, it is good to know that these two are equivalent.
doSomething with the Maybe will look like this:
Here we have three functions,
map that can be composed together into a new single function. We can pass value into that new function and it will flow through first into
toMaybe and finally that value will flow into our
And for one last picture perfect Tweet:
I hope you enjoyed this small functional journey. Let me know in the comments if you did, if you got lost, if you have any questions, or if you want more articles like this one. If you really want to motivate me, follow me here or and if you loved this article, pass it around!
p.s. this article was originally posted on dev.to.