Javascript function return function

I have a simple demo:

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

Now when I call add(1)(2), he will give me3

but I want something like this:

add(1)(2)(3) β†’ 6

add(1)(2)(3)(4) β†’ 10

this means that I can add more features if I want. How to write it down?

+4
source share
3 answers

I saw a similar problem elsewhere, but there the requirement was somewhat different. Instead of having add(1)(2)(3)return 6, you would need to have add(1)(2)(3)()return 6.

, . , , , , . undefined ( NaN) , currying .


, , add(1)(2)(3)() 6. :

  • , add , , .

  • undefined ( NaN), .

  • , sum, total .

function add(x) {
  var sum = x;
  return function total(y) {
    if (!isNaN(y)) {  
      sum += y;
      return total;
    } else {
      return sum;
    }
  }
}

console.log(add(5)(2)());
console.log(add(5)(3)());
console.log(add(1)(2)(3)(4)());
Hide result
+7

-

var arr = [1,2,3,4];

function add(a , i, sum) {
    if(i >= a.length ){ 
      return sum;
    } else {
      sum = sum + a[i];
      ++i;
      return add(a, i, sum)
    }
}
var b = add(arr ,i=0,sum = 0);
console.log(b)
0

If you want to work with an array. Only if someone goes for him, since Nisarg's answer is absolutely low.

function add(a) {
    arrInt = a;
    return function total(arrInta) {
        b = 0;
        arrInt.forEach(element => {
            b = b + element;
        });
        return b;
     };
 }

 a = [1,2,3]

 console.log( add(a)());
 a = [1,2,3, 4]
 console.log( add(a)());

What returns:

​​​6​​​​​ at ​​​add(a)​​​ ​quokka.js:14:1​

​​​​​10​​​​​ at ​​​add(a)​​​ ​quokka.js:16:1​
0
source

Source: https://habr.com/ru/post/1695385/


All Articles