skip to Main Content

We need to create a function that would print the results for:
console.log(sum(1)(2)(3)(4)(5)(6)());

So this is how I did:

let res = 0;
function sum(a){
  if(a){
    res = res + a;
    return sum; //Return the same function for next chain of actions
  }else{
    return res;
  }

}
console.log(sum(1)(2)(3)());

Is there a way I can achieve this with a local res? the problem I face with making it local is, it just gets reset in the next call.

I see some solutions like this:

function sum(a) {
  return function(b){
    if(!b){
        return a;
    }
    return sum(a+b);
  }
}

But the way I did appears more natural and intuitive to me and I just want to make that work with res as local instead of gloabl.

2

Answers


  1. You could do it like this:

    The innerSum function maintains a closure over res. This allows res to retain its value across multiple calls to innerSum.

    function sum(a) {
      let res = a;
      function innerSum(b) {
        if (b !== undefined) {
          res += b;
          return innerSum;
        } else {
          return res;
        }
      }
      innerSum.toString = function() {
        return res;
      };
      return innerSum;
    }
    

    Demo

    function sum(a) {
      let res = a;
      function innerSum(b) {
        if (b !== undefined) {
          res += b;
          return innerSum;
        } else {
          return res;
        }
      }
      innerSum.toString = function() {
        return res;
      };
      return innerSum;
    }
    
    console.log(sum(1)(2)(3)(4)(5)(6)().toString());
    Login or Signup to reply.
  2. You can make the sum an IIFE and put res in the local scope. After that, when called with no arguments, reset the res to 0 to make it ready for the next call.

    const sum = (() => {
      let res = 0;
      
      return function (a) {
        if (typeof a === 'number') {
          res = res + a;
          return sum;
        } else {
          const temp = res;
          res = 0;
          return temp;
        }
      }
    })();
    
    console.log(sum(1)(2)(3)());
    console.log(sum(1)(2)(3)(4)());

    It can also be shortened in a simpler but maybe cursed syntax:

    const sum = (res => a => {
      if (typeof a === 'number') {
        res = res + a;
        return sum;
      }
      
      try {
        return res;
      } finally {
        res = 0;
      }
    })(0);
    
    console.log(sum(1)(2)(3)());
    console.log(sum(1)(2)(3)(4)());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search