FizzBuzz Challenge
Instructions
Write a function that accepts a start and end number and prints:
Fizzif divisible by 3Buzzif divisible by 5FizzBuzzif divisible by both 3 and 5- The current number if divisible by neither
Examples
Here are a few examples to illustrate how the fizzbuzz function works:
Example 1
Input: start = 0, end = 5
Output: ['FizzBuzz', 1, 2, 'Fizz', 4, 'Buzz']
Example 2
Input: start = 10, end = 15
Output: ['Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz']
Solution
The example solution provided demonstrates a function called fizzbuzz that returns an array of results for each number in the range from start to end. The function checks each number and appends the appropriate string or number to the result array.
FizzBuzz
const fizzbuzz = (start, end) => {
const result = [];
for (let i = start; i <= end; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result.push('FizzBuzz');
} else if (i % 3 === 0) {
result.push('Fizz');
} else if (i % 5 === 0) {
result.push('Buzz');
} else {
result.push(i);
}
}
return result;
}
In this example, the function is implemented using a recursive approach.
FizzBuzz Recursive
const fizzbuzzRecursive = (start, end, result = []) => {
if (start > end) return result;
if (start % 3 === 0 && start % 5 === 0) {
result.push('FizzBuzz');
} else if (start % 3 === 0) {
result.push('Fizz');
} else if (start % 5 === 0) {
result.push('Buzz');
} else {
result.push(start);
}
return fizzbuzzRecursive(start + 1, end, result);
}