Sherif Wael
Sherif Wael

Reputation: 455

Calling a function with multiple parenthesis

While doing some JavaScript challenges, I faced with the code add(1)(2), a function being called with several parenthesis. The challenge is to make a chain of add function.

add(1)(2)(3);       // -> 6
add(1)(2)(3)(4);    // -> 10
add(1)(2)(3)(4)(5); // -> 15

Also, we should be able to store the returned values and reuse them.

var addTwo = add(2);

addTwo;       // -> 2
addTwo + 5;   // -> 7
addTwo(3);    // -> 5
addTwo(3)(5); // -> 10

Thanks in advance.

Upvotes: 1

Views: 111

Answers (1)

Sashi yadav
Sashi yadav

Reputation: 358

 function sum(firstArg, opt_argsStack) {
    const argsStack = (opt_argsStack || []).concat([firstArg]);

    const nextSum = nextArg => sum(nextArg, argsStack);
    nextSum.valueOf = () => argsStack.reduce((a, b) => a + b);
    return nextSum;
    }

    console.log(+sum(1));
    console.log(+sum(1)(2));
    console.log(+sum(1)(2)(3));
    console.log(+sum(1)(2)(3)(4));

Here, we pass the stack of all accumulated arguments down to recursive call. And in valueOf call, stack is transformed to a number via reduce just in time. This gives us more flexibility, imo, if we wanted to change chained sum to chained multiplication or whatever else — we just plug in different reduce function.

refer:https://medium.com/reflecting-on-bits/fun-fact-sum-of-numbers-through-infinite-currying-in-js-a5c229765a18

Upvotes: 1

Related Questions