0

I was trying to solve a puzzle which takes 'n' arguments and then computes sum.

function add(arg1) {
    let total=arg1;
    const func = function(...args){
        if(!args[0]) return total;
        total += args[0];
        return func;
    }

    return func;
}

console.log(add(1)(2)(3)()); // => Should output 6

Question: Using the same logic above example, I am trying to do this:

What if I want to do something like

sum(1)(2)(3) => should give 6

If i do sum(1) => Should output 1

sum(1)(2) => should output 3 and so forth.

This is what I've tried:

function sum2(num) {
    let total = num;

    const fn = function(...args) {
        if(args[0]) total += args[0];
        return total;
    }

    return fn();
}

console.log(sum2(1)) //=> Works
console.log(sum2(1)(2))// => Fails
TechnoCorner
  • 4,879
  • 10
  • 43
  • 81

1 Answers1

1

Explanation:

Proxy : The Proxy object is used to define custom behaviour for fundamental operations. In javascript you can create traps for pretty much every operation

  • Used Getter function of the handler to return Sum
  • Used Apply function of the handler to iterate and perform addition.

function sum2(n) {
  sum = n;
  const adhoc = new Proxy(function a () {}, {
    get (obj, key) {
      return () => sum;
    },
    apply (receiver, ...args) {
      sum += args[1][0];
      return adhoc;
    },
  });
  return adhoc
}
console.log(sum2(1));
console.log(sum2(1)(2));
console.log(sum2(1)(2)(3));
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47