0

I want to implement the function in javascript let say Add that should support bellow formats

add(a,b,c)
add(a)(b)(c)
add(a)(b,c)
add(a,b)(c)

All these should return a+b+c. Is it possible? if so how?

Harish
  • 1,841
  • 1
  • 13
  • 26

2 Answers2

1

You can do something like

function add(){
    let sum = 0;
    for(let e of arguments) sum += e;
    let ret = add.bind(null, sum);
    ret.toString = () => sum;
    ret.valueOf = () => sum;
    return ret;
}


let x = +add(2, 3)(4)(11)
console.log(x, typeof x);
marvel308
  • 10,288
  • 1
  • 21
  • 32
1

Whenever the function is run collect the arguments object parameters into an array, and check it's length. If the length of the array is 3 or greater sum the first 3 numbers using Array#reduce. If not, return the function.

function add() {
  var args = []; // collect the arguments

  function innerAdd() {
    args.push.apply(args, arguments); // add the arguments to args
    
    // if the length of args is under 3 return innerAdd, if not sum the first 3 numers
    return args.length < 3 ? innerAdd : args.slice(0, 3).reduce(function(s, n) {
      return s + n;
    });
  }
  
  return innerAdd.apply(null, arguments); // invoke innerAdd with current arguments
}

var a = 1, b = 2, c = 3;

console.log(add(a,b,c));
console.log(add(a)(b)(c));
console.log(add(a)(b,c));
console.log(add(a,b)(c));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209