Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to understand how a function works that is run with two parentheses and two parameters. Like so:

add(10)(10); // returns 20

I know how to write one that takes two params like so:

function add(a, b) {
  return a + b;
}

add(10,10); // returns 20

How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?

Any help is appreciated. Literally scratching my head over this.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
422 views
Welcome To Ask or Share your Answers For Others

1 Answer

How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?

You can almost do that, but I'm struggling to think of a good reason to.

Here's how: You detect how many arguments your function has received and, if it's received only one, you return a function instead of a number — and have that function add in the second number if it gets called:

function add(a,b) {
  if (arguments.length === 1) {
    return function(b2) { // You could call this arg `b` as well if you like,
      return a + b2;      // it would shadow (hide, supercede) the one above
    };
  }
  return a + b;
}
console.log(add(10, 10)); // 20
console.log(add(10)(10)); // 20

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...