Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Created September 28, 2023 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/3392c85a9e922af0fa7ed71b806ef4b6 to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/3392c85a9e922af0fa7ed71b806ef4b6 to your computer and use it in GitHub Desktop.
The classic Fizz Buzz but without using the if...else if... else solution
const fizzBuzzMap = {
3: 'Fizz',
5: 'Buzz',
15: 'FizzBuzz'
};
/**
* The classic "Fizz Buzz" game: Print a list of numbers from 1 to the upper limit, using the following rules:
* * If the number is divisible by 3 print "Fizz"
* * If the number is divisible by 5 print "Buzz"
* * If the number is divisible by 3 and 5, print "FizzBuzz"
*
* @param {number} upperBound The excluive (i.e. up to but not including) limit to which Fizz Buzz should be played
* @returns {string} A comma-separated string with the approprate numbers replaced with the "Fizz Buzz" text
*/
function fizzBuzz(upperBound) {
const result = [];
const keys = Object.keys(fizzBuzzMap);
for (let i = 1; i < upperBound; i++) {
let value = i;
keys.forEach(key => {
if (i % key === 0) {
value = fizzBuzzMap[key];
return;
}
});
result.push(value);
}
return result.join(', ');
}
console.log(fizzBuzz(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment