Arguments Optional - Can this one be solved with currying?

Tell us what’s happening:
I was hoping to be able to solve this one with some sort of currying behaviour but I failed (instead I used the rest operator to solve it). If anyone can message me a possible solution with currying I would be grateful for the opportunity to learn!

Your code so far


function addTogether(x, ...arg) {
  if (arg.length == 0) {
    if (Number.isInteger(x)) {
      return function (y) {
        if (Number.isInteger(y)) {
          return x+y;
        }
      };
    }
  } else {
    if (Number.isInteger(arg[0]))
     return x + arg[0];
  }
}

addTogether(2,3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional

Hi @hbar1st

You are using currying, by catering for the use-case where the function is called like this: addTogether(2)(3). You are splitting the arguments up into a sequence of evaluations (function calls), which is essentially what currying is. See here for more info.

Thanks joe, I didn’t realise that. I was trying to figure out a way to use the bind operation but nothing i could think of worked. Do you know if there is a way to use it here?

Bind only works on existing functions, so you could do this:

function addTogether(x, ...arg) {
  if (arg.length === 0) {
    if (Number.isInteger(x)) {
      return function(x, y) { // extra paremeter here
        if (Number.isInteger(y)) {
          return x + y
        }
      }.bind(null, x) // function bound here
    }
  } else {
    if (Number.isInteger(arg[0])) {
      return x + arg[0]
    }
  }
}

However, in the case of currying, it kinda adds unnecessary code and makes it a little unreadable. Anybody that understands JS and closure will know whats happening with your code, using bind complicates it a little.

1 Like