Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to achieve currying with a local variable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading