Write a JavaScript curry function to add n numbers

Curry function uses JavaScript closure concepts. JavaScript closure remembers the previous lexical scope.

Using the closure concepts we can write a JavaScript curry function to add n numbers. Following is an example:

    function add(a) {
        let callback = function (b) {
            a += b;
            return callback;
        };
        callback.toString = () => a;
        return callback;
    };

    console.log(+add(1)(2));  
    // Output: 3
 

If we want every consecutive call to increment by one, we can use the following code:

    function add() {
        let sum = 1;
        let callback = function (b) {
            sum++;
            return callback;
        };
        callback.toString = () => sum;
        return callback;
    };

    console.log(+add()());   
    // Output: 2

    console.log(+add()()());
    // Output: 3   
Reference