At the risk of misunderstanding the issue here, I wanted to share a tactic I just stumbled upon for a similar situation.
Problem:
The problem, in my case, is that sometimes I need to call a function (foo
) with some arguments without changing the this
context. Unfortunately, the list of arguments is not deterministic-- sometimes there might be 2, sometimes there might be 3, etc. And since _.partial
expects each argument to be passed in as a separate argument, I was initially stumped. For example:
// some dynamic array of args
var args = [new Error(), [{id: 3}, {id: 7}], function cb() {}];
// the function we want the partially applied to
var fn = function foo ( /* ...want `args` in here... */ ) {
// ..implementation...
}
// can't do it with normal _.partial() usage...
// var newFn = _.partial(fn, args[0], args[1], ... args[args.length])
Solution:
This is much the same use case when you'd want to use apply
instead of call
to invoke a function normally. So after putzing around w/ it for a while, I realized I could just do:
var argsToLodashPartialFn = [foo].concat(args);
var newFn = _.partial.apply(null, argsToLodashPartialFn);
tldr;
Or, more concisely:
var newFn = partialApply(foo, args);
// === newFn(args[0], args[1], ...., args[n])
newFn();
And here's the implementation as a reusable function:
/**
* partialApply()
*
* Like `_.partial(fn, arg0, arg1, ..., argN)`,
* but for a dynamic array of arguments:
*
* @param {Function} fn
* @param {Array} args
* @return {Function}
*/
function partialApply (fn, args) {
return _.partial.apply(null, [fn].concat(args));
}