TIL about more examples of currying
POSTED ON:
TAGS: javascript advanced
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: javascript