Today I Learned - Rocky Kev

TIL about more examples of currying

POSTED ON:

TAGS:

Currying is nothing more than a way to transform functions that accept multiple parameters into a sequential list of functions that take only one parameter each.

It looks like this:

console.log(curriedSum(1)(2)) //outputs 3

It's mostly coming from a math/functional programming world, where you pass data from one set to another. (like a factory!)

Explain more

Breaking down this example into real code.
Using another example:

// original code
const add = (a, b, c) => a + b + c;

add(1, 2, 3);

// the curry version
const curry => (a) => {
return (b) => {
return (c) => {
return a + b + c
}
}
}

curry(1)(2)(3)

Functions are just labels. Behind the scenes, javascript is replacing the whole function's label with the actual code.

Uses

Usecase 1 - separating arguments

const sendRequest = greet => name => message =>
`${greet} ${name}, ${message}`

sendRequest('Hello')('John')('Please can you add me to your Linkedin network?')

// response
// "Hello John, Please can you add me to your Linkedin network?"

Usecase 2 - formulas

function converter(toUnit, factor, offset, input) {
offset = offset || 0;
return [((offset + input) * factor).toFixed(2), toUnit].join(" ");
}

var milesToKm = converter.curry('km', 1.60936, undefined);
var poundsToKg = converter.curry('kg', 0.45460, undefined);
var farenheitToCelsius = converter.curry('degrees C', 0.5556, -32);

milesToKm(10); // returns "16.09 km"
poundsToKg(2.5); // returns "1.14 kg"
farenheitToCelsius(98); // returns "36.67 degrees C"

via https://stackoverflow.com/a/6861858/4096078

Overall

I'm not a super big fan of currying. In terms of functional programming, I like the concept! And in terms of code readability, it does make your data much more straightforward.

Unless my team is full of math wizs, I try to stay away from currying.

Currying for JavaScript Developers with Examples


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.