0

I need to add the function n number of arguments. Example : add(3)(8)(6)(10).

if it is only 2 arguments we can add the code like this. add(4)(5)

function add(x){
    return function(y){
       return x+y;
    }
}
add(4)(5)

if it is n number of arguments of how can we do this?

Venu G
  • 11
  • 1
  • 2
  • 3
    You want `add(3)(8)(6)(10) === 27`, for any number of terms? That’s impossible. You can have something that acts like a number, but it won’t really be one (and that would be a terrible API). – Ry- Apr 03 '18 at 03:46
  • Do you know `n` a priori? – c2huc2hu Apr 03 '18 at 03:47
  • https://stackoverflow.com/questions/39187590/how-to-curry-a-function-across-an-unknown-number-of-parameters/39198247#39198247 – slebetman Apr 03 '18 at 04:17
  • Or even [Variadic curried sum function](https://stackoverflow.com/q/5832891/4642212). – Sebastian Simon Apr 03 '18 at 04:19

3 Answers3

3

The closer I can get to what you asked is this;

function add(x){
    var next = function(y){
       return add(x + y)
    }

    next.result = x
    return next
}

console.log(add(4)(5).result)
console.log(add(4)(5)(1)(5).result)
console.log(add(3).result)

Here is a slightly different approach using objects, and IMO it is a lot more readable then add(1)(2)(3) since it is clear what operation you are performing in the subsequent steps. Also, this approach allows for extending with more operations, like minus for example.

class Add {
    constructor (value) {
        this.value = value
    }

    add (anotherValue) {
        return new Add(this.value + anotherValue)
    }

    result () {
        return this.value
    }
}

function add (value) {
    return new Add(value)
}

var result = add(3).add(5).add(10).result()
console.log(result) // 18
Renato Gama
  • 16,431
  • 12
  • 58
  • 92
0

If n is not known beforehand, I can say categorically it's not possible. If n is fixed, you can do something like (say, n is 4):

const add = first => second => third => fourth => first + second + third + fourth.

If you want to let n be flexible, your best bet is this

const add = (...additives) => {
  let result = 0;
  for (const additive of additives) {
    result += additive;
  }
  return result;
}
Huy Nguyen
  • 2,840
  • 1
  • 14
  • 18
0

As Ryan suggested in his comment : add(3)(8)(6)(10) is impossible.

Try this work around :

function add() {
  var sum = 0;
  for (var i = 0; i < arguments.length; i++) {
    sum = sum+arguments[i];
  }
  return sum;
}

var res = add(3, 8, 6, 10);
console.log(res);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123