DEV Community

Discussion on: FizzBuzz JavaScript

Collapse
ttatsf profile image
tatsuo fukuchi • Edited on

Here another way to make it easier to modify it :

const FIZZBUZZ_RULE = 
      [
        {num:3, text:"Fizz"}
        , {num:5, text:"Buzz"}
        , {num:7, text:"Foo"}
        , {num:11, text:"Bazz"}
      ]

const fizzBuzz = n =>
  FIZZBUZZ_RULE.reduce(
    (acc, e) => 
       ! isDividable(e.num)(n) ? acc
       : ! acc.dividable ? {val:e.text, dividable:true}
       : {...acc, val:acc.val + e.text} 
    , {val:n, dividable:false}
  ).val

const isDividable = m => n => 
  n % m === 0

// Example:
fizzBuzz(3*5*7*11)  //  'FizzBuzzFooBazz'

for(let i = 1; i < 16; i++) console.log( fizzBuzz(i) )
/*
1
2
'Fizz'
4
'Buzz'
'Fizz'
'Foo'
8
'Fizz'
'Buzz'
'Bazz'
'Fizz'
13
'Foo'
'FizzBuzz'
*/

You can add/remove a rule in FIZZBUZZ_RULE.