Currying - JavaScript

//English

<!-- What is currying? -->

Currying is when you break a complex function into a serie of functions. It means that if you have a function that takes 2 arguments, you can break it into 2, each one will receive one parameter, something like this:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 //Complex Function  
 function greetingsComplex(msg,name){  
   console.log(msg+', '+name);  
 }  
 //Simple Function  
 function greetingsEasy(msg){  
   return function(name){  
     console.log(msg+', '+name);  
   }  
 }  
 greetingsComplex('Hello','Carlos');  
 greetingsComplex('Hello','Ulises');  
 greetingsComplex('Hello','Hector');  
 var greetings = greetingsEasy('Hello');  
 greetings('Carlos');  
 greetings('Ulises');  
 greetings('Hector'); 

As you can see above, it's easier to understand the easiest way than the complex, Instead to call a function 3 times with multiple parameters, we call one to set the general values, the ones that you are not going to change, and return a function which takes the values that you usually change.

If you need to change the message, just call the function: greetingsEasy with a different msg and assign the returned value to the variable: greetings:


1
greetings = greetingsEasy('Good Morning!');

But, how Currying works? Internally, when you call the main function (greetingsEasy), you set the message, so this value is saved in memory, and then return a new function (greetings), then you call the returned function (greetings) with the name you want, let's say: Carlos; When the returned function (greetings) is executed, this function can access to the values of its parents!, that's why greetings can access to the value msg.

<!-- Conclusion -->

Currying is a technique used to break complex functions into small functions, this would be easier to use, maintain and understand. You can create an entire program using just this technique. If you want to see it in action, see the code below (to execute it, just type the command: node [file name] on the terminal):



//Español

Muy pronto...

Comments

Popular posts from this blog

Juego de Gato Usando HTML, JavaScript y CSS

AfterEffects - Quitar el Fondo de un Video Forma 1: KeyLight

Crear un nuevo Libro de Excel con VBA ES