DEV Community

Discussion on: Fizz Buzz in Every Language

Collapse
 
avalander profile image
Avalander

Since nobody has done Javascript yet, here's a crazy implementation.

const worder = (predicate, patterner) => (prev, n) =>
  predicate(prev, n)
    ? patterner(prev, n)
    : prev

const isDivisible = d => (_, n) =>
  n % d === 0

const isEmpty = s =>
  s.length === 0

const append = x => (prev) => prev + x

const setNumber = (_, n) => n

const fizzer = worder(isDivisible(3), append('fizz'))

const buzzer = worder(isDivisible(5), append('buzz'))

const numberer = worder(isEmpty, setNumber)

const reducer = (...worders) => n =>
  worders.reduce(
    (prev, w) => w(prev, n),
    ''
  )

const fizzbuzzer = reducer(
  fizzer,
  buzzer,
  numberer
)

for (let i = 0; i <= 100; i++) {
  console.log(fizzbuzzer(i))
}

Consider how easy it is to extend to print 'fazz' for multiples of 7.

const fazzer = worder(isDivisible(7), append('fazz'))

const fizzbuzzfazzer = reducer(
  fizzer,
  buzzer,
  fazzer,
  numberer
)
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

I appreciate the commitment to the obscure. Haha these are great.

Collapse
 
avalander profile image
Avalander

That's the whole point of the exercise, right? :D

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Oh absolutely! Got any code golf solutions?

Thread Thread
 
avalander profile image
Avalander • Edited

Hmm... the best I can come up with right now is 85 chars. Nothing really clever, just sacrificed readability for space.

let i=0;while(i++<101){console.log(i%15==0?'fizzbuzz':i%5==0?'buzz':i%3==0?'fizz':i)}

Another fun one, albeit longer, is this.

console.log(new Array(101)
  .fill(1)
  .map((_, i) =>
    i % 15 == 0 ? 'fizzbuzz' :
    i % 3 == 0 ? 'fizz' :
    i % 5 == 0 ? 'buzz' :
    i
  )
  .slice(1)
  .join('\n'))