Add(1)(2)(3)…(n)() in Javascript | Sum(1,2)(3,4) | Currying | Javascript Interview | Walmart
Case 1: add(1)(2)(3)
It’s basically a sequence of functions with single argument. So our approach is to return a function which in turn returns another function to accept next argument.
function add(a){ return function(b){ return function(c){ return a+b+c } } }
It’s basically a sequence of n+1 functions with single argument except the last one. So our approach is to return a function which in turn returns another function to accept next argument and so on till the last argument doesn’t exist.
function add(a) { return function(b){ if(b){ return add(a+b) } return a } }
Case 3: sum(1,2)(3,4)
So, this is similar as above just that we are accepting two arguments in single call. So, we need to add the arguments. Let’s look at the code:
function sum(a,b) { return function(c,d){ return a+b+c+d } }
Case 4: add(1,2..n)(5,6…n)…(n)()
Now in this case, everything is infinite. We already know infinite currying, let’s focus on infinite arguments.
function add(...args) { let a = args.reduce((a, b) => a + b, 0) return function(...args){ let b = args.reduce((a, b) => a + b, 0) if(b){ return add(a+b) } return a } }
So this is complex, right? You won’t be asked this question during your initial years of Javascript Interview but you never know. So, what’s happening here is, we are using inbuilt rest operators to take infinite arguments and then calculating the sum of all arguments. Rest remains the same as case 2.
If you have followed this far, do check out How to flatten a nested array in JS | Recursion | Javascript Interview | 1
Check out 100 JAVASCRIPT INTERVIEW QUESTIONS TO CRACK ANY JAVASCRIPT INTEVIEW
Amazon Front End Interview Experience and Questions
Yeah, share your solutions in comments section and do let me know if you want me to share my frontend interview experience at Walmart and Makemytrip. In case you want to schedule a call with me for any discussion about career or finding international opportunities, here is the link.


2 Comments
Harish
Great blog, really appreciate all your effort. This link is not working – https://www.niksbay.com/2020/04/100-javascript-interview-questions-to-crack-any-javascript-inteview.html . I would like to know if the updated link.
Thanks for maintaining blog and sharing all your experiences and knowledge, very helpfull 🙂
Nikscode
Thanks for reading my blog. I have updated the link. Recently moved my blog to this domain.