Exercise – Functional FizzBuzz
by patrickliang
JavaScript
/**
* Exercise:
*
* FizzBuzz Function
*
* Work in the console, or use "console.log()" to output to the console
* from the script
*
* The FizzBuzz rules...
* - for numbers that are a multiple of 3,
* log "Fizz" instead of the number
* - for numbers that are a multiple of 5
* log "Buzz" instead of the number
* - for numbers that are a multiple of both,
* log "FizzBuzz" instead of just Fizz or Buzz
*
* 1) Implement the fizzbuzz function:
* - It accepts a single number argument
* - Outputs the correct response to the console based on the FizzBuzz rules
*
* 2) Create a loop that executes your fizzbuzz function for the numbers from 1 to 100
*
* 3) BONUS 1 - write tests
* use console.assert() to verify your function works as expected
* ex: console.assert(fizzbuzz(3) === "Fizz");
*
* 4) BONUS 2 - refactor your function
*
*/
function fizzbuzz(n) {
// 1) implement the function
if (n % 3 === 0 && n % 5 === 0) {
console.log("FizzBuzz");
console.log(n);
return "FizzBuzz";
}
else if (n % 3 === 0) {
console.log("Fizz");
console.log(n);
return "Fizz";
}
else if (n % 5 === 0) {
console.log("Buzz");
console.log(n);
return "Buzz";
}
/*refactored code
var result = '';
if (n%3===0) {
result += "Fizz";
}
if (n%5===0) {
result += "Buzz";
}
*/
}
// 2) run the function with a loop
for (var i = 1; i < 101; i++) {
fizzbuzz(i);
}
// 3) BONUS 1
// use console.assert() to test your function
console.assert(fizzbuzz(3) === "Fizz");
console.assert(fizzbuzz(10) === "Buzz");
console.assert(fizzbuzz(30) === "FizzBuzz");