How to sum numbers using closures in Javascript?


interview javascript

Two numbers

I was asked to write the following function using the closures:

sum(x)(y) = x + y;

I knew the solution and wrote it fast, but only for two numbers:

function sum(x) {
	return function (y) {
		return x + y
	}
}

This solution is suitable, but only for two numbers.

Infinite brackets

But then I was asked to change my function to support infinite number of brackets. For example:

sum(x)(y)...(z) == x + y + ... + z
// sum(1)(-1)(2)(3) == 5 // true

I have been stuck on this and now I’m sorting out the solution. Here is the solution to this task:

function sum(x) {

  let currentSum = x;

  function f(y) {
    currentSum += y;
    return f;
  }

  f.toString = function() {
    return currentSum;
  };

  return f;
}

How it works? I will show based on this example:

console.log(sum(1)(3)(-1) == 3) // true
  1. sum function is evaluated
  2. currentSum is 1
  3. f function is returned
  4. f function is evaluated
  5. y is 3, we plus it to currentSum. After currentSum is 4
  6. f function is returned
  7. f is executed again
  8. y is -1, we plus it to currentSum. Now currentSum is 3
  9. f function is returned
  10. On this step string conversion happens, because f is using with ==. Because f is a function object, it should contain toString method, and it calls while stringing conversion. However, we override f.toString and return currentSum
  11. sum(1)(3)(-1) == 3 is true
comments powered by Disqus