settingsAccountsettings
Menusettings

Q: Functional Sum (task with advanced JavaScript functions)

+3 votes

Write a function that adds a number passed to it to an internal sum and returns itself with its internal sum set to the new value, so it can be chained in a functional manner.

Input:
Your function needs to take one numeric argument.

Output:
Your function needs to return itself with updated context.

Examples:

Sample Input:

console.log(add(1));

Output:

1


Sample Input:

console.log(add(1)(6)(-3));

Output:

4

asked in JavaScript category by user hues

1 Answer

+2 votes

Making a function return itself is easy enough, but to keep a sum that’s shared across all instances requires some effort. You’ll need to place it inside a closure and expose just the function. Finally, to get the stored value, you’ll have to override the built-in toString() method that all JavaScript objects have so that it returns the internal sum – this will allow any other function to access it either for printing or to use it in an expression, without being able to modify it. You can attach it directly to your function from inside the closure.

Note that NodeJS will not implicitly call toString() when you try to log a value to the console. Keep this in mind when testing your solution locally.

My solution to the task:

let solve = (function () {
    let sum = 0;

    return function add(number) {
        sum += number;
        add.toString = function () {
            return sum;
        };
        return add;
    }
})();

console.log(solve(1)(6)(-3).toString());
answered by user ak47seo
edited by user golearnweb
...