Currying Nowadays - Javascript
<!-- English -->
Hi guys, It's been a while since the last time I wrote, sorry for that, anyways, today's post is about currying, if you don't know what is currying about, don't worry, take a look of my previous post (I strongly recommend you to read it if you don't know what currying is about), if you do, you can continue reading.
Well it looks like you want to go on...so let´s start; When we say currying in js, you usually think in something like this:
function Parent(){ return function Child(){ //Your code } }
Well that´s how we used to do currying, now there´s a different way to do it, thanks to Function.prototype.bind(), let´s see how the function we have above can be easily replaced for the following code:
function Parent(){ //Your code } var Child = Parent.bind(null);
NOTE: Maybe you'll be curious about the null we passed, well basically we're going to tell to the function in which context is it going to be executed, don't worry about it, I'll explain the context in JS in future posts :)
But how do we use the currying in real life? let's say we wan't to create a custom logger, with a prefix before the log, something like this:
My Awesome Logger : a log message
Using currying that we used to do, would be something like this:
function PrefixLogger(prefix){ return function(msg){ console.log(prefix, msg); } } var logger = PrefixLogger('My Awesome Logger :'); logger('a log message');
Pretty awesome, right? well, let´s do an small refactor to our code to using the nowadays currying:
var logger = console.log.bind(null,'My Awesome Logger :'); logger('a log message');
This is even more awesome! But how the bind works? Basically the definition of bind says:
"...Function.prototype.bind will return a new function taking as its first parameter the context in which it's going to be executed, and then the values to the Function separated by commas..."
In common words, when we do this:
var newConsoleLog = console.log.bind(null,'My Awesome Logger :');
We are returning a new function based on the function: console.log, we don't care about the context, so we pass null as the first parameter, and then our prefix. Internally JS will do a wrapper similar to the one we do above (The currying of the old days...).
Take a look at mi ideone to see it working. Well guys this is it for today, if you have doubts or questions, don't hesitate to reach me :) either through here or Twitter. See you guys ^_^/
See this practical example to have a clearer Idea of how cool is bind!
Comments
Post a Comment