OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Is there a way to achieve currying with a local variable

  • Thread starter Thread starter ABGR
  • Start date Start date
A

ABGR

Guest
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:


Code:
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:

Code:
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.

<p>We need to create a function that would print the results for:
<code>console.log(sum(1)(2)(3)(4)(5)(6)());</code></p>
<p>So this is how I did:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>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)());</code></pre>
</div>
</div>
</p>
<p>Is there a way I can achieve this with a local <code>res</code>? the problem I face with making it local is, it just gets reset in the next call.</p>
<p>I see some solutions like this:</p>
<pre><code>function sum(a) {
return function(b){
if(!b){
return a;
}
return sum(a+b);
}
}
</code></pre>
<p>But the way I did appears more natural and intuitive to me and I just want to make that work with <code>res</code> as local instead of gloabl.</p>
 

Latest posts

Online statistics

Members online
0
Guests online
4
Total visitors
4
Top