Cooking with javascript? What? 🤷♂️
Currying is a technique, where a function takes several parameters as input and returns a function with exactly one parameter.
Currying is a fundamental tool in functional programming, a programming pattern that tries to minimize the number of changes to a program’s state (known as side effects) by using immutable data and pure (no side effects) functions.
Now, let's cut to the chase. Check this code example:
const isDivisible = (divider, number) => !(number % divider);
const divider = 2;
console.log(isDivisible(divider, 40)); // true
console.log(isDivisible(divider, 33)); // false
In the previous code, isDivisible
is a function expression that checks whether one number is divisible by another, returning true or false, as simple as that.
If my intention in the three isDivisible
calls is to use the same divisor, isn't it tedious and tedious having to pass the divisor as a parameter every time I want to know if a number is divisible by two?
Just changing the isDivisible
function and making the divisor a fixed value.
But we would have a gigantic coupling impacting a non-reusable and fully cast function
And now is the time for our game star to step in
Currying 🤓
const isDivisible = divider => number => !(number % divider);
console.log(isDivisible(2)(40)); // true
console.log(isDivisible(2)(33)); // false
console.log(isDivisible(3)(40)); // false
console.log(isDivisible(3)(33)); // true
Therefore now we have a decoupled and flexible function, not only dependent on number two and can be used in any situation we want to know if a number is divisible or not 🧐
🍻