DEV Community

Discussion on: Currying Inside JavaScript

Collapse
 
puiutucutu profile image
puiu • Edited

Nice function - one thing I noticed is that calling the curry function's callback with all the arguments provided at once or one at a time, you get back the same result.

For example:

const adder = (x, y) => x + y;
const curriedAdder = curry (adder);

const a = curriedAdder (1) (2); //=> 3
const b = curriedAdder (1, 2);  //=> 3
Enter fullscreen mode Exit fullscreen mode

I would also recommend throwing an error when there is a mismatch between the number of supplied args and the number of args the function actually needs.

For example, the code below will throw a different error when the curried function is partially applied versus when then curried function is called with all arguments at once.

const isEveryArgumentProvided = x => y => x >= y;

function curry(f) 
{
  function curried(...initialArgs) {
    if (initialArgs.length > f.length) {
      throw new Error(
        `Function \`${f.name}\` supplied ${initialArgs.length} args when expecting ${f.length} args`
      );
    }

    return isEveryArgumentProvided (initialArgs.length) (f.length)
      ? f.apply(this, initialArgs) // received all args for f
      : (...remainingArgs) => curried.apply(this, [...initialArgs, ...remainingArgs])  // more args needed for f
    ;
  }

  return curried;
}

const adder = (x, y) => x + y;
const curriedAdder = curry(adder);

curriedAdder (1) (2) (3); //=> Error: curriedAdder(...)(...) is not a function
curriedAdder (1, 2, 3); //=> Error: Function `adder` supplied 3 args when expecting 2 args
Enter fullscreen mode Exit fullscreen mode