Give an example how "currying" might be used in JavaScript:
const component = (argument1) => (argument2) => {
// Do something
}
Give an example how "currying" might be used in JavaScript:
const component = (argument1) => (argument2) => {
// Do something
}
That is called function currying. It is useful for implementing the decorator pattern among others.
For example, let's say we start with a simple function add
.
const add = (a, b) => a + b;
console.log(add(1, 2));
Now, let's say we want to add two numbers but also add ten every time.
We could do this:
const add = (a, b) => a + b + 10;
console.log(add(1, 2));
But, then we lose our original function.
So we use function currying to do both:
// We keep the original add function
const add = (a, b) => a + b;
// And create another function that returns the modified function
const addTen = (addFunction) => (a, b) => 10 + addFunction(a, b);
// then we store the new function in a different variable
const addPlusTen = addTen(add);
// ...and call the returned function
console.log(add(1, 2));
console.log(addPlusTen(1, 2));
// This becomes useful when we need to make an addPlusFive, addPlusSix and addPlusSeven functions:
const addFive = (addFunction) => (a, b) => 5 + addFunction(a, b);
const addSix = (addFunction) => (a, b) => 6 + addFunction(a, b);
const addSeven = (addFunction) => (a, b) => 7 + addFunction(a, b);
const addPlusFive = addFive(add);
const addPlusSix = addSix(add);
const addPlusSeven = addSeven(add);
console.log(addPlusFive(1, 2));
console.log(addPlusSix(1, 2));
console.log(addPlusSeven(1, 2));
In your code there are two arrow functions, one returns the other which can help you to maintain state/scope using Closure
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
const multiplier = (argument1) => (argument2) => {
return argument2 * argument1;
};
const multiples8 = multiplier(8);
console.log(multiples8(5));
console.log(multiples8(6));
console.log(multiples8(7));
What you are doing is called chaining.
const add = (a) => (b) => {
return a + b;
}
var add5 = add(5); // returns partially applied function
var result = add5(4); // which can be invoked with its own parameter
console.log(result); // 9
Arrow function provides cleaner syntax since if there is one parameter you can omit parenthesis around the arguments, and if function body is single line you can omit the square brackets. We could write same code using regular js function syntax:
const add = function(a){
return function(b){
return a + b
}
}
Your code have short versions of two nested arrow functions. Here is how full version looks (with return statement and brackets it should looks more clear):
let component = (argument1) => {
// console.log(argument1);
return (argument2) => {
// console.log(argument2);
}
}
component('aa')('bb');
First function (with argument1) return FUNCTION. That returned function take argument2.