Skip to content

Instantly share code, notes, and snippets.

@rousan
Last active September 29, 2020 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rousan/0f83aba57bfc579308ec86cee1a7942c to your computer and use it in GitHub Desktop.
Save rousan/0f83aba57bfc579308ec86cee1a7942c to your computer and use it in GitHub Desktop.
Solution: sum(1)(2)(3)(10)() = 16

Solution: sum(1)(2)(3)(10)() = 16

  1. Solution 1: Cache the value in the function itself. But, It will not work when the function is called multiple times at the same time.
function sumAggr(num) {
  if (sumAggr.sum === undefined) {
    sumAggr.sum = 0;
  }
  
  if (num === undefined) {
    let temp = sumAggr.sum;
    sumAggr.sum = 0;
    return temp;
  } else {
    sumAggr.sum += num;
    return sumAggr;
  } 
}
  1. Solution 2: The optmized soltion.
function sumAggr2(num1) {
  let sum = num1;
  
  return function closore(num2) {
    if (num2 === undefined) {
      return sum;
    } else {
      sum += num2;
      return closore; 
    }
  }
}

console.log(sumAggr(1)(2)(3)(10)());
console.log(sumAggr2(1)(2)(3)(10)());

console.log(sumAggr(1)(2)(3)(10)());
console.log(sumAggr2(1)(2)(3)(10)());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment