2

When using bind in JS, one can create functions with predefined arguments, e. g.:

var add = function (a, b) {
    return a + b;
};
var addToThree = add.bind(null, 3);

But how to I do this if I want to predefine the second, third etc. argument, but not the first?

lupor
  • 138
  • 7
  • 1
    the tool you want, rpartial(), is available in several functional libraries. – dandavis Dec 31 '15 at 02:51
  • 1
    [underscore's partial()](http://underscorejs.org/#partial) also allows for passing the underscore reference to skip an argument. But aside from a library function, I don't think there is "built-in" js way to rpartial or skip an argument in a partial application using bind. – J. Holmes Dec 31 '15 at 03:37

2 Answers2

1

In ES2015 you can do something like this:

const partial = fn => (...pargs) => (...args) => fn.apply(null, [...pargs, ...args]);
const partialRight = fn => (...pargs) => (...args) => fn.apply(null, [...args, ...pargs.reverse()]);

const myFunc = (one, two, three, four) => {
  console.log(one);
  console.log(two);
  console.log(three);
  console.log(four);
};

const myFuncPartial = partial(myFunc)('1');

const myFuncPartialRight = partialRight(myFuncPartial)('4', '3');

myFuncPartialRight('2');
cstuncsik
  • 2,698
  • 2
  • 16
  • 20
0

You can do

var add = function (a, b) {
    b = b || 5;
    return a + b;
};

In ES6 Default Parameters can be used in a very easy way

var add = function (a, b=5) {
    return a + b;
};

and call it like add(3);

void
  • 36,090
  • 8
  • 62
  • 107
  • Thanks for the tip, but this is not what I'm looking for. I want to create functions from existing functions, without changing the originals. In your example, add includes stuff which it shouldn't need to know (the default parameter), since adds' job is only to add two numbers together. – lupor Dec 31 '15 at 01:54