I am learning recursive functions. For fun, I tried the FizzBuzz coding challenge.
I am stuck as I don't understand why I can't reverse my array inside the recursive function.
Version 1
const fizzBuzzRecursive = num => {
let results = [];
if (num === 1) {
return '1';
} else {
if (num % 3 === 0 && num % 5 === 0) {
results.push('FizzBuzz');
} else if (num % 5 === 0) {
results.push('Buzz');
} else if (num % 3 === 0) {
results.push('Fizz');
} else {
results.push(''+ num);
}
newResults = results.reverse('')
return newResults.concat(fizzBuzzRecursive(num - 1));
}
}
console.log(fizzBuzzRecursive(5));
// prints [ 'Buzz', '4', 'Fizz', '2', '1' ]
To make it work, I have to place the recursive function inside another function.
Version 2
const fizzBuzz = num => {
const fizzBuzzRecursive = num => {
let results = [];
if (num === 1) {
return '1';
} else {
if (num % 3 === 0 && num % 5 === 0) {
results.push('FizzBuzz');
} else if (num % 5 === 0) {
results.push('Buzz');
} else if (num % 3 === 0) {
results.push('Fizz');
} else {
results.push(''+ num);
}
return results.concat(fizzBuzzRecursive(num - 1));
}
}
return fizzBuzzRecursive(num).reverse()
};
console.log(fizzBuzz(5));
// prints [ '1', '2', 'Fizz', '4', 'Buzz' ]
Why does version 1 not properly and is there a way to make it work? Thanks in advance!
In your first example, you are reversing an array with a single element, then concatenating it with the array returned by the next recursive call. In effect, this will not reverse anything, and the results will be concatenated together starting at the deepest level of recursion.
const fizzBuzzRecursive = num => {
let results = [];
if (num === 1) {
return ['1'];
} else {
if (num % 3 === 0 && num % 5 === 0) {
results.push('FizzBuzz');
} else if (num % 5 === 0) {
results.push('Buzz');
} else if (num % 3 === 0) {
results.push('Fizz');
} else {
results.push(''+ num);
}
return fizzBuzzRecursive(num - 1).concat(results);
}
}
console.log(fizzBuzzRecursive(5));
// prints [ '1', '2', 'Fizz', '4', 'Buzz' ]
To achieve the reversal, simply swap the order of the concatenation, also making sure to return ['1']
inside of an array as your base case to make sure that it is able to concatenate with the other recursive calls.