Implement an infinite sum function
The classic infinite sum problem is probably the most repetitive brain teaser problems I have encountered during my interviews focussing on testing knowledge of closures alongside recursion.
Itβs arguably one of my favourite questions as well just by the sheer number possible variations it can have π .
1. Basic implementation
Implement a sum function which can perform addition of the input values passed to it in the given form. In this case, only one argument can be passed at a time.
const result= sum(1)(2)(3)(4)()
should yield a result of 10
.
2. Sporadic input implementation
In this variation, there is no restriction of passing only a single input at a time. Some possible ways to invoke the sum function can be:
-
const result1=sum(1)(2,3,4)()
-
const result2=sum(1,2,3)(4)()
-
const result3=sum(1,2,3,4)()
-
const result4=sum(1,2)(3)(4)()
3. Sporadic input with fixed arguments length implementation
Untill now, all the variations of infinite sum the termination was either no input or empty input passed to the function. However in this variation, we still need to allow sporadic input, but only upto fixed length or size. Some possible invocation in this variation are:
-
const result1=sum(1)(2,3,4)
-
const result2=sum(1,2,3)(4)
-
const result3=sum(1,2,3,4)
-
const result4=sum(1,2)(3)(4)
-
const result5=sum(1)()(2)(3)(4)
-
const result6=sum(1)()()()()(2,3,4)
We assume that the fixed length here is 4, i.e total of 4 arguments;
Further Reading
I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing π«‘.