Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bind as a method for currying

I was watching a video on youtube about functional programming. They had gotten through some basic currying stuff (still trying to really grasp that), 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 accomplishing things, but not the urls with bind. I know that bind returns another function, but I'm not picking up on how the current value being iterated of the array (i.e. the "path") is being set and used through bind.

like image 707
noob-in-need Avatar asked Nov 01 '25 12:11

noob-in-need


1 Answers

When you use Function.prototype.bind like this:

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

it results into new function that is used as a callback function passed into map. This new function is invoked with two additional parameters: "http" and "www.firefox.com". So virtually it looks something like this:

paths.map(function(path) {
    return simpleURL.call(null, "http", "www.firefox.com", path);
});
like image 186
dfsq Avatar answered Nov 04 '25 03:11

dfsq