Created
September 28, 2023 14:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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