Functional programing with JavaScript: Extract the n-th parameter and send it to a function as parameter
05:45 08 Jun 2015

Let's say I have an API, which offers me a function, that has to be augmented with two parameters: an "settings" object and a callback function, to which 3 parameters will be sent.

As an example the request package in node.js:

var request = require("request");

request({
   uri: "http://www.something.com"
}, function(error, response, body) {
   doSth(body);
});

As you can see, the only thing I intend, is to extract the body of the response and process it further.

Is there any shorter solution for the task "extract one argument and send it to a function"?. Here are the approaches:

var arg2funct = 
function arg2funct(nr, funct) {
  return function() {
    funct(arguments[nr]);
   }
}

request({ uri: "http://www.something.com" }, arg2funct(2, doSth) );

Or with underscore:

__ = require("underscore");

var arg2funct = function(nr, funct, x, y, z) { funct(arguments[nr+2]); };
request({ uri: "http://www.something.com" }, __.partial(arg2funct, 2, doSth) );

The question now is: How can the function become more general? Because this one works only if the callback awaits 3 parameters (x, y, z).

And also: Is there maybe a better way to solve this with the underscore library? Or: do I maybe have to switch to another one.

javascript node.js functional-programming underscore.js