Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use currying and partial functions in JavaScript

I read this post on Dr. Dobb's about currying and partial functions in JavaScript. It looks useful, but I'm wondering (as an occasional developer in JavaScript) if there are standard situations where this is regularly used?

like image 620
conrad carter Avatar asked Oct 28 '11 17:10

conrad carter


2 Answers

For starters, I personally wouldn't recommend currying in 99% cases. It can easily make code unreadable if used improperly.

However, some of the applications that I could name would be associated with setting the function context. For example when you first execute the currying function with a context (something other than window object etc), you could have a function that applies certain calculations on the original object's properties etc when called later.

Second situation would be when, for example, you have a function that takes three arguments. The DOM element, the attribute name and it's value. This could be turned into a currying function that you could initiate with the appropriate element, then each following execution would set an attribute to the value you wish. Might be useful in cases, where you have numerous conditionals on which the attributes depend.

like image 143
zatatatata Avatar answered Sep 30 '22 20:09

zatatatata


A very common scenario is when creating event handlers.

For example, say you have a document with a lot of links such as:

    <a href="http://someurl.com/example">link</a>

Say you want to have javascript go through and make all these links display a "You are now going to: <link_url>" dialog box on click. In that case, you could use code such as:


    var links = document.getElementsByTagName("a"), len = links.length;
    for (var n = 0; n < len; ++n) {
        links[n].onclick = window.alert.bind(null, "You are now going to: " + links[n].innerText);
    }

Function.prototype.bind() (which I use on window.alert()) is very similar to the partialApply() used in the article that you link.

While this example itself isn't that practical, it is not far from a more common task: Displaying a confirmation box when the user clicks on a link that leads to a third party web site.

Now, instead of window.alert.bind(...), we could have used an anonymous function:


    links[n].onclick = (function(text) {
        return function() { window.alert(text); };
    })("You are now going to: " + link[n].innerText);

However that is a lot more code! Most examples of currying can be "simplified" in this way, so it usually only serves as a shortcut, albeit a very handy one.

like image 40
George Avatar answered Sep 30 '22 20:09

George