1

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.

3
  • can you share the code in your post please? Commented Dec 10, 2018 at 11:45
  • What programming language ? Commented Dec 10, 2018 at 11:48
  • I edited the post . It is JavaScript , sorry if you found my post little messy it is my first question and i haven't get used to it yet .Thanks Commented Dec 10, 2018 at 12:55

1 Answer 1

1
 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

Sign up to request clarification or add additional context in comments.

2 Comments

Got it. Thanks a lot I really appreciate your help.
@Sashi yadav Do not forget to quote the original resource from where you copied the solution. medium.com/reflecting-on-bits/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.