Partial lodash.js application for function.

Given the following function, using the function _.partialraises an error:

function foo(x, y) { return 1 + 2; }
p = _.partial(foo.apply, null);
p([1,2]);

I get:

TypeError: Function.prototype.apply was called in [object Window], which is an object, not a function

What am I doing wrong here? Is there any other way to achieve what I am doing?

+4
source share
3 answers

I believe in this, that you are going to:

function foo(x, y) { return x + y; }
p = Function.apply.bind(foo, null);
p([1,2]); // ===3

the closest I can get the underscore to do it is through _.bind:

function foo(x, y) { return x + y; }
p = _.bind(foo.apply, foo, 0);
p([1,2]); // ===3

you can also consider another flexible use of this function to summarize an entire array of more than two elements:

 function foo(x, y) { return x + y; }
_.reduce([1,2,3,4,5], foo); // == 15

or using vanillaJS:

function foo(x, y) { return x + y; }
[1,2,3,4,5].reduce(foo); // == 15
+3

, .

:

, (foo) this. , - 2, 3 .. _.partial , , . :

// 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])

:

, apply call . , , , :

var argsToLodashPartialFn = [foo].concat(args);
var newFn = _.partial.apply(null, argsToLodashPartialFn);

TL;DR;

, :

var newFn = partialApply(foo, args);

// === newFn(args[0], args[1], ...., args[n])
newFn();

:

/**
 * 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));
}
+2

lodash 3.2, spread() :

function foo(x, y) { return x + y; }
var p = _.spread(foo);
p([ 1, 2 ]); // → 3
+1
source

Source: https://habr.com/ru/post/1531434/


All Articles