javascriptfunctional-programmingcurryingfunction-binding

Generalised Curry - Javascript


While reading an article on implementation of a generalised curry in Javascript, I stumbled upon this piece of code.

function curry(fn) {
  return (...xs) => {
    if (xs.length === 0) {
      throw Error('EMPTY INVOCATION');
    }
    if (xs.length >= fn.length) {
      return fn(...xs);
    }
    return curry(fn.bind(null, ...xs));
  };
}

I am unable to grok the part of the explanation which states

We create a copy of fn that has the first k arguments bound (partially applied) and pass it to curry as the next fn, with its reduced arity of N - k.

How does the arity of fn reduced to N-k in the subsequent calls? A bound function with k arguments should have an arity of k right?


Solution

  • A bound function returns a function with partially applied arguments, so f(a, b, c) becomes f.bind(null, a).bind(null, b)(c).