4

So recently I discovered that you can do partial functions/currying with js using bind. For example:

const foo = (a, b, c) => (a + (b / c))
foo.bind(null, 1, 2) //gives me (c) => (1 + (2 / c))

However this only works if the parts you want to curry are in order. What if I wanted to achieve the following using bind?

(b) => (1 + (b / 2))

Tried various solutions such as:

foo.bind(null, 1, null, 2)

Any ideas? Is it possible to accomplish this with vanilla es6?

duplode
  • 33,731
  • 7
  • 79
  • 150
Vangogh500
  • 939
  • 1
  • 7
  • 17
  • 1
    with placeholders, you could have a look to this question: https://stackoverflow.com/questions/48327804/javascript-callback-for-two-functions – Nina Scholz Jun 05 '18 at 20:19
  • 1
    There is a proposal for partial application syntax sugar https://github.com/tc39/proposal-partial-application – Yury Tarabanko Jun 05 '18 at 20:25

2 Answers2

3

You could use a wrapper for a reordering of arguments.

const
    foo = (a, b, c) => a + b / c,
    acb = (a, c, b) => foo(a, b, c);

console.log(acb.bind(null, 1, 2)(5));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Currently I think about two ways to implement this (besides the wrapper from @NinaSholz, which is pretty nice):

1. Using a curry function that merges two argument arrays:

const foo = (a, b, c) => a + b / c;

function curry(fn, ...args) {
  return function(...newArgs) {
    const finalArgs = args.map(arg => arg || newArgs.pop());
    return fn(...finalArgs);
  };
}

const curriedFoo = curry(foo, 1, null, 2);

console.log(curriedFoo(4)) // Should print 1 + 4 / 2 = 3

Here we are just sending null or undefined in the place of the parameters we want to skip and in the second call we send those parameters in order

2. Using objects for named parameters

const foo = ({a, b, c}) => a + b / c;

function curry(fn, args) {
  return (newArgs) => fn({ ...args,
    ...newArgs
  });
}

const curriedFoo = curry(foo, {
  a: 1,
  c: 2
});

console.log(curriedFoo({
  b: 4
}));

Here we are taking advantage of the ...(spread) operator and object syntax in the funcion signature to merge two argument objects;

J. Pichardo
  • 3,077
  • 21
  • 37