Functional JavaScript: Function lComposition For Every Day Use.

PIRO4D

Function composition has got to be my favorite part of functional programming. I hope to provide you with a good real world example so not only do you understand function composition, but so you can begin using today! In this article will learn how to write as well as organize your files, so you can write short, clean and functional code like this…

…that will produce output like this…

Head straight to the codepen if you want to tinker. Continue reading to start learning :)

The Basics

We have to walk before we can run, so let’s start with the boring stuff that you need to know.

Function composition is a mathematical concept that allows you to combine two or more functions into a new function.

You have probably stumbled across this example when googling function composition. If you haven’t yet, I assure you, you will.

I myself am guilty of using this example and what I failed to realize is that the student is not yet able to see how this can be practically applied in their codebase today. Instead they are comparing that example with something like this:

const value = (x + 2) * 3

It is hard to see why you would prefer the functional example.

A teacher’s failure to properly provide good real world examples will result in a student’s failure to understand why.

Hopefully I can do a better job of demonstrating the power of function composition.

Back to Basics

A key to function composition is having functions that are composable. A composable function should have 1 input argument and 1 output value.

You can turn any function into a composable function by currying the function. I’ll expand on currying in another article, but you should still be able to follow along without knowing what currying is.

You might do html stuff, so that’s a good point to start. Let’s make a tag. (I’m going to be working with strings here, but you could also do this with React).

const tag = t => contents => `<${t}>${contents}</${t}>`
tag('b')('this is bold!') 
> <b>this is bold!</b>

I also want a function to handle tags with attributes like <div class="title">...</div>. So I’ll add another function to handle this use case.

Sprinkle in a little refactoring to combine it all into these four functions…

Now we can call tag with a string or an object.

Making Something Real

Now that you’ve made it through that boring stuff, you deserve some fun code.

Let’s use that fancy new tag function to create something tangible. We can use something easy and something familiar, bootstrap’s list group.

First, let’s create a function for each of these tags and listGroupItems to support multiple listGroupItems.

If we look at the structure of the list-group html we can see that there is one outer element that contains multiple children. Since it will always be created this way, it seems a little verbose to call listGroup(listGroupItems([‘Cras justo’, ‘Dapibus ac’])) to render the list every time.

I should just be able to call listGroup([‘Cras justo’, ‘Dapibus ac’]). The function should know what I want to do.

To do this I’ll start by renaming listGroup to listGroupTag. That way I can create a new listGroup function that will encapsulate the call to listGroupTag(listGroupItems([])).

Function Composition

For those of you that skipped the whole article and scrolled all the way down to this section, you might be disappointed. Composing the functions is actually the easiest part of the whole process. After you have created your functions to be composable, they just kind of snap together.

Take a look at the code below. Any time you recognize this pattern, the functions can be easily composed.

const listGroup = items =>
listGroupTag(listGroupItems(items))

When composed together, the result will look similar to the original, listGroupTag on the left, followed by listGroupItems, and then items on the right.

const listGroup = items =>
compose(listGroupTag, listGroupItems)(items)

Let’s look at them side-by-side so we can see the similarities and differences.

When functions are composed together, they are read from right to left just like regular functions.

Because compose returns a function that takes a list and our listGroup function also takes a list, we can simplify listGroup to equal our composition and remove list.

const listGroup =
compose(listGroupTag, listGroupItems)

By now your mind is probably not blown and I understand. Out of all this code we have written, function composition helped us simplify only a single line of code.

The power of function composition is realized as your codebase grows, allowing you to create numerous compositions.

So let’s add a bootstrap panel.

Now if we want to create an element that is a list-group inside of a panel, all we have to do is this:

const listGroupPanel =
compose(basicPanel, listGroup)

The (above) function is also equivelant to this (below). You can compose any amount of functions!

const listGroupPanel =
compose(basicPanel, listGroupTag, listGroupItems)

Organizing Your Code

Organizing your code is also very important. This involves separating your functions into multiple files.

I like to create a file called functional.js and this is where I put compose and related functional functions.

All of the functions we created above I would put in html.js.

I am also creating a dom.js for DOM manipulation (you will see in the codepen.)

Breaking our code out into multiple library files allows us to reuse these functions in other projects.

Now when we write the main program in main.js, there will be very little code.

The Example

I can’t break up the codepen example into multiple files, so I have separated them using comments so you can see how to properly layout your files.

I put the final app up on codepen , so you can tinker with it.
https://codepen.io/joelnet/pen/QdVpwB

The Math

Originally I had some stuff here, but you don’t need to know gravity's equation to know objects attract.

Compose and Pipe

It is also worth mentioning, compose has a companion function pipe. pipe also composes functions, but in reverse order. In some situations, it can be easier to understand when it’s written left to right (or top down).

// pseudo code
const login = pipe(
validateInput,
getCustomer,
getAuthToken
loginResponse)

Here are the functions, I would recommend putting these in a functional.js library that you can include in all your projects.

Summary

Function composition requires you to write your functions in a composable way. This means your functions must have 1 input and 1 output. Functions with multiple inputs must be curried.

Composing functions is not only easy but fun too.

You will achieve the highest level of code reuse with function composition.

making our code reusable should always be one of our goals.

My next article will be about composing asynchronous functions. I thought I could fit it all into a single article, but this page got long quickly. So let’s just stop it here. Subscribe so you do not miss out on Part 2!

I know it’s a small thing, but it makes my day when I get those follow notifications on Medium and Twitter (@joelnet). Or if you think I’m full of shit, tell me in the comments below.

Cheers!

Related Articles

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.