Function Factories & Currying
The goal of a function factory is to create a main function that you can copy multiple times, each time setting the initial argument to a different value. Thus, you write one function, and can create an infinite amount of additional functions just by binding the first parameter to a different value.
This article is an extension to my more extensive article on currying.
Let’s take the simple add function.
let add = (x, y) => x + y;
You can then create a copy of that function with the first value set to 2 and call it add2, you can copy the function again and set the first argument to 3 and call it add3. The ability to create copies of the main function with a slight variation to its parameters is the idea behind creating a function factory, and that also is a loose definition of currying.
let add2 = add.bind(this, 2);
let add3 = add.bind(this, 3);
let add10 = add.bind(this, 10);
let add100 = add.bind(this, 100);
let add1000 = add.bind(this, 1000);
But this is a bit of a contrived example just so you understand the concept. Let’s use something a little more real world.
const greetLoggedInUser = (language) => { return (firstName) => { if(language === 'en'){
console.log(`Welcome ${firstName}!`);
} if(language === 'es'){
console.log(`Bienvenido ${firstName}!`);
} }}
Here we will create a factory function that accepts a language as its argument. When that function is called a language will be saved in a closure and given to the function that it returns. That function will take in a first name as its argument. When that function is called it will return a message in the language saved in the closure.
let greetLoggedInUserInEnglish = greetLoggedInUser('en');
let greetLoggedInUserInSpanish = greetLoggedInUser('es');greetLoggedInUserInEnglish('Jamie');
greetLoggedInUserInSpanish('Jamie');
As I come across other examples that I think are important for understand function factories and currying I will post them here, but you should get the idea.