Using binding as a currying method

I watched a video on youtube about functional programming. They got some basic stuff (still trying to figure it out) and then they showed a way that you could use bind as a "soft" curry er.

function simpleURL(protocol, domain, path) {
  return protocol + "://" + domain + "/" + path;
}

var paths = ["search?query=dogs", "search?query=cats"];

/*
var urls = paths.map(function(path) {
  return simpleURL("http", "www.firefox.com", path);
});
*/

var urls = paths.map(simpleURL.bind(null, "http", "www.firefox.com"));

console.log(urls); // --> ["http://www.firefox.com/search?query=dogs", "http://www.firefox.com/search?query=cats"]

      

I understand the commented way of doing things, but not urls

with linking. I know that bind returns a different function, but I don't understand how the current value being iterated over by the array (ie "Path") is set and used via bind.

+3


source to share


2 answers


When you use Function.prototype.bind

, follow these steps:

simpleURL.bind(null, "http", "www.firefox.com")

      



it results in a new function that is used as the callback function passed to map

. This new function is called by two additional parameters: "http" and "www.firefox.com". In practice, it looks something like this:

paths.map(function(path) {
    return simpleURL.call(null, "http", "www.firefox.com", path);
});

      

+2


source


The function returned by simpleURL.bind (null, "http", "www.firefox.com") works the same as the original function, but the protocol and domain are always "http" and "www.firefox.com", and now it only takes one argument, which is the path value.



When you call the map function, it passes each array value to your new function, and that value becomes the path value.

0


source







All Articles