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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With