Skip to content Skip to sidebar Skip to footer

Create Function To Add Such That Add(1,2)(3,...k)(1,2,3)...(n) Should Sum All Numbers

I have been looking for a way to create an 'add' function such that : add(1,2) //returns 1+2= 3 add(1)(2,3)(4) // returns 10 add(1)(2,3)(4)(5,6)(7,8,9) //returns 45 I am able to c

Solution 1:

It's not possible in the general case unless toString coercion is allowed on the result of calling add (or unless the number of calls is known in advance):

functionadd(...next) {
  let count = 0;
  // return a callable function which, when coerced to a string,// returns the closure's `count`:functioninternalAdd(...next) {
    count += next.reduce((a, b) => a + b, 0);
    return internalAdd;
  }
  internalAdd.toString = () => count;
  returninternalAdd(...next);
}

console.log('' + add(1,2)) //returns 1+2= 3console.log('' + add(1)(2,3)(4)) // returns 10console.log('' + add(1)(2,3)(4)(5,6)(7,8,9)) //returns 45

Post a Comment for "Create Function To Add Such That Add(1,2)(3,...k)(1,2,3)...(n) Should Sum All Numbers"