Skip to content

Instantly share code, notes, and snippets.

@topheman
Created May 29, 2018 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save topheman/26839181f7091efa2c4a0f9419536841 to your computer and use it in GitHub Desktop.
Save topheman/26839181f7091efa2c4a0f9419536841 to your computer and use it in GitHub Desktop.
JavaScript Implementation of FizzBuzz in functional programming
// http://wiki.c2.com/?FizzBuzzTest
const result = Array.from(Array(100), (_, i) => i + 1).map(number => {
if (number%5 === 0 && number%3 === 0) {
return "FizzBuzz";
}
if (number%3 === 0) {
return "Fizz";
}
if (number%5 === 0) {
return "Buzz";
}
return number;
});
console.log(result.join('\n'))
@andreobriennz
Copy link

andreobriennz commented Jul 26, 2019

What about this?

const isFizz = number => number % 5 === 0
const isBuzz = number => number % 3 === 0

const newArrayInRange = (min, max) => [...Array(max + 1).keys()].slice(min)

const fizzBuzz = (min, max) => newArrayInRange(min, max)
  .map((number) => {
    if (isFizz(number) && isBuzz(number)) {
      return 'fizzbuzz'
    }
    if (isFizz(number)) {
      return 'fizz'
    }
    if (isBuzz(number)) {
      return 'buzz'
    }
    return number
  })
  .join('\n')

console.log(fizzBuzz(1, 100))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment