Created
January 20, 2023 11:57
-
-
Save kolja/23fc06b0468bf8de420ce56b7db604e6 to your computer and use it in GitHub Desktop.
JavaScript FizzBuzz
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
// first naive, straight-forward solution: | |
function divides(a,b) { | |
return a % b === 0; | |
} | |
for (i=1; i<20; i++) { | |
if (divides(i,3) && divides(i,5)) { | |
console.log("fizzbuzz"); | |
} else if (divides(i,3)) { | |
console.log("fizz"); | |
} else if (divides(i,5)) { | |
console.log("buzz"); | |
} else { | |
console.log(i); | |
} | |
} | |
// now onto a more functional approach: | |
function divides(a,b) { | |
return a % b === 0; | |
} | |
function range(n) { | |
return [...Array(n).keys()]; | |
} | |
function fizzbuzz(range, rules) { | |
return range.map( i => | |
rules.reduce( (acc, rule) => acc + rule(i), '') || i | |
) | |
} | |
const rules = [ | |
x => divides(x, 3) ? 'fizz' : '', | |
x => divides(x, 5) ? 'buzz' : '' | |
] | |
console.log( fizzbuzz( range(20), rules )); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment