Write a function that takes an input character and returns that character repeated 5 times using recursion. For example, if the input is 'g', then the output should be 'ggggg'.
I tried the code below:
function repeater(char) {
let newStr = '';
if (newStr.length === 5){
return newStr;
}
else {
newStr += char;
}
return repeater(char);
}
// To check if you've completed the challenge, uncomment these console.logs!
console.log(repeater('g')); // should return 'ggggg'
//console.log(repeater('j')); 'jjjjj'
My code returns: RangeError: Maximum call stack size exceeded
What am I doing wrong?
Cause newStr
is a local variable that does not get passed on in the recursive call. Therefore, a new newStr
will be created on each call, and its length will always be 0. To resolve that, either pass on the string, or the length:
function repeat(char, result = "") {
if(result.length / char.length >= 3) return result;
return repeat(char, result + char); // ²
}
// a call goes like:
// repeat("g", "")
// repeat("g", "g")
// repeat("g", "gg")
// repeat("g", "ggg")
// OR
function repeat(char, count = 3) { /*¹*/
if(count <= 1) return char;
return char + repeat(char, count - 1);
}
// repeat("g", 3)
// "g" + repeat("g", 2)
// "g" + "g" + repeat("g", 1)
// "g" + "g" + "g"
Or if this should only work with one char given (as the task says):
function repeat(char) {
if(char.length >= 3) return char;
return repeat(char + char[0]); // ²
}
Note: The functions above won't return 5 repeats. Thats left as an exercise to you :)
If we take the assignment aside you could just do "g".repeat(5)
though ...
¹: The = 3
is a so called "default argument". That means that repeat("g")
equals repeat("g", 3)
. The advantage is that you can reuse this for different lengths, repeat("g", 10)
will repeat g 10 times.
²: Thats a tail call. If you place the recursive call at the last line and return it, the engine can optimize the recursion into a loop, which is way faster and does not reach a maximum call stack size (infinite recursion is still bad, try to always avoid getting into it. newStr.length === 5
for example is dangerous, as a string of length 6 would run forever. Therefore I'd recommend using >=
or <=
(as I did above)).
You could take a default value of 5
and call the recursion until no more calls are a available.
function repeater(char, count = 5) {
if (!count) return ''; // exit condition
return char + repeater(char, count - 1); // repeating part
}
console.log(repeater('x'));
One thing in your code is you are calling repeater outside else condition which means it will be called infinitely. Second is you are declaring newStr inside the function. You may want to do something like this.
function repeater(char, oldStr) {
let newStr = oldStr || '';
if (newStr.length === 5) {
return newStr;
} else {
newStr += char;
return repeater(char, newStr);
}
}