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.
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
sum
function is evaluatedcurrentSum
is 1f
function is returnedf
function is evaluatedy
is 3, we plus it to currentSum
. After currentSum
is 4f
function is returnedf
is executed againy
is -1, we plus it to currentSum
. Now currentSum
is 3f
function is returnedf
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
sum(1)(3)(-1) == 3
is true