I finally found a reason to curry
April 25, 2018, 6:43 pm

Currying functions is not necessarily a hard concept to understand. It goes like this: You make a function that returns a function for something else to call as a function.


Hold on. Let me give you an example.

var a = function(num1) { return function(num2) { return num1 + num2; } } var b = a(3); var c = b(3); // output 6;

But here's the thing. That example really makes no sense. What's going on here? And why would I do this?

Well first of all, you wouldn't. That's a too simplistic bad example. I can see you saying "I would just make one function with two parameters" and you would be right of course. That's a much better use for that example.

But what if you needed a kind of a function that needed to do some things, and prepare some things, and then have a unique kitchen table prepared for a meal to be prepared again and again in the future?

What if you needed a table command that prepared a particular kind of bread. And then anyone could come along to the table they liked and make sandwiches out of the bread at that table. Sandwiches always get made the same way, but the bread needs to be prepared first.

var makeBread = function(breadtype){ return function(jamType,pbType) { return `${pbType} and ${jamType} on ${breadtype}`; } } var wheatSandwich = makeBread("wheat"); var sandwich1 = wheatSandwich("jelly","creamy pb"); var sandwich2 = wheatSandwich("marmalade","crunchy pb");

So now we don't have to define wheat anymore. It's part of the function. But using the original makeBread sandwich we could still define another style of sandwich if we wanted to.

I recently found currying useful while working on my drawtools library. Currying a tool for loading images into a canvas allows me to set up a function that caches a particular image into it's own memory to then draw onto a canvas.