title: Implementing Sum Function in javascript
body: <p>I was trying to solve a puzzle which takes 'n' arguments and then computes sum.</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>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)()); // =&gt; Should output 6</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>Question:</strong> Using the same logic above example, I am trying to do this: </p>
  
  <blockquote>
    <p>What if I want to do something like </p>
    
    <p>sum(1)(2)(3) => should give 6</p>
    
    <p>If i do sum(1) => Should output 1 </p>
    
    <p>sum(1)(2) => should output 3 and so
    forth.</p>
  </blockquote>
  
  <p>This is what I've tried: </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>function sum2(num) {
      let total = num;
  
      const fn = function(...args) {
          if(args[0]) total += args[0];
          return total;
      }
  
      return fn();
  }
  
  console.log(sum2(1)) //=&gt; Works
  console.log(sum2(1)(2))// =&gt; Fails</code></pre>
  </div>
  </div>
  </p>