I am trying to make the code below repeat string s
n
number of times, however, it will always repeat n - 1
times, because I need to pass a decrement to exit the recursion or I will exceed the max call stack.
JavaScript
x
8
1
function repeatStr (n, s) {
2
while(n > 1) {
3
result = repeatStr(-n, s)
4
return s = s.concat(s)
5
}
6
}
7
repeatStr(3, "Hi")
8
What can I change to make it recurse correctly?
Advertisement
Answer
Recursion involves making a function call itself and AVOIDS using a loop. You have a loop in the recursive function which is a big red flag.
Do something like this: If n is 1 return s else return s concatenated to the result of the function with n – 1.
JavaScript
1
8
1
function repeatStr (n, s) {
2
if (n == 1)
3
return s;
4
else
5
return s.concat(repeatStr(n - 1, s))
6
}
7
repeatStr(3, "Hi")
8