Currying to decrease code complexity: a refactor experiment

Sebastiaan Nijland
Kaartje2go
Published in
3 min readMay 1, 2018

A few months back, our backenders implemented a nice enhancement to the image upload paths. We could request the images at any size we fancied by changing a few placeholders. The drawback: the JavaScript to do this got quite messy (in my opinion), since we needed a lot of logic for this.

I started out implementing this in a quite verbose way, but soon realized that this would become unwieldy. Have a look below at a simplified version, for the purposes of this post.

The actual code needed to account for retina images, different image extensions with different quality settings and be able to provide .webp versions — you can imagine the amount of logic.

Simplified example of the initial code

There are some quick wins here, like extracting the switch case into a separate function and maybe using a ternary for the if/else.

This still didn't feel good enough to me.

Currying

I've been reading about currying and this felt like a nice piece of code to refactor/experiment with.

First things first, what is currying in a nutshell? It is a mathematical technique to rewrite a single function that takes multiple arguments into a sequence of functions which take one argument each.

Take for example the old code you see above. We could rewrite this function with four arguments into this:

Curried function example

It looks like not much changed, but the power of this function really shines when you look at an example of it's usage in a Picture Component:

Using the function in a Picture

We now have four new functions, each of which take just a width param and prefill the image and screenSize. I took some magic numbers for the widths and then doubled that for retina: in the actual code, I added a more generic factor param to calculate the width.

I'm pretty excited about curried functions! To me, they make the code a lot more readable and more reusable. I'm still experimenting a bit, but I can definitely see myself applying this technique more often in the near future!

Have you tried out curried functions yourself? Please feel free to leave a comment with your ideas on this!

Notes

I didn’t include this in the post for readability purposes, but if you're going to use any of this for production code, I really recommend moving all magic numbers to a Constants file or some similar solution.

In case you’re not sure about the arrow functions, which really make this example shine to me, you can read more about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

In the last example I use template literals. In case you’re not sure about those, you can read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

--

--