Arguments Optional - currying

Tell us what’s happening:
I’m having trouble understanding currying. Basically, I think I have the code the way I want it to pass all tests except when I need to curry. I just don’t understand how to write it I keep thinking about recursion but I don’t think currying is the same. recursion seems to call the function again with a new argument but it’s my understanding that when currying you call the function with all parts at once.

Your code so far


function addTogether() {
if ((typeof arguments[0] !== 'number') || (typeof arguments[1] !== 'number')){
  return undefined;
  } else if (arguments.length === 1){
  return arguments[0];
  } else if (arguments[1] !== undefined) {
  return (arguments[0] + arguments[1]);
  } else {
    //curry
    a => b => return a + b;
  }

}


addTogether(2, 3);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: Arguments Optional

Link to the challenge:

Currying is nothing magical - it’s just returning a function. In this case, if you pass it two arguments, it should add and return that number. If you pass one argument, it should return a function that will request another argument.

So:

const result1 = addTogether(2, 3); // returns the number 5

const nextStepFunction = addTogether(2); // returns a function that will take in a parameter and add it to 2
const result2 = nextStepFunction(3); // returns the number 5

const result3 = nextStepFunction(2)(3); // does the same as the previous, but in one line

Mathematically, that’s all currying is, breaking up a function that takes multiple parameters that take smaller functions that teach the different parameters:

x = f(a, b)

becomes

g = f(a)
x = g(b)

in other words:

x = f(a)(b)

Yeah, it’s a little weird at first, returning functions, etc. It just takes practice. I always recommend checking out youtube - watching someone do it can sometimes make it easier to understand.

1 Like

Recursion is a process that refers to the very object of the process at a point in the process. In other words, it is an approach whose description leads to the repetition of the same rule. Here you can’t call addTogether function within itself because it doesn’t describe itself in computation.
Instead Currying is when you transform a function with several arguments to a function with a single argument which return a function with a single argument untill the arguments length filled.
So you can write this

function doAddition(a){
  return function(b){
    return a + b;
  }
}

instead of writing
function doAddition(a,b){return a + b;}