DEV Community

Discussion on: Unconditional Challenge: FizzBuzz without `if`

Collapse
 
kallmanation profile image
Nathan Kallman

Clever! I'll accept it for the normal challenge :)

If you want hard mode though, I think you'll have to show an implementation of .filter that doesn't use if, ?:, ||, &&, ?., or ??. (I'll allow .reduce to be used though, as well as .map)

Well done, thanks for commenting!

Collapse
 
avaq profile image
Aldwin Vlasblom • Edited

Okay, well, my next solution is probably not what you were expecting. It builds on the idea that a boolean can be used as a number. I think it meets the hardcore requirements.

const isFizz = n => n % 3 === 0
const isBuzz = n => n % 5 === 0
const isNeither = n => !isFizz(n) && !isBuzz(n)

// the magic:
const optional = (f, x) => Array(Number(f(x))).fill(x)

const fizzbuzz = n => {
  const fizz = optional(isFizz, n).map(_ => 'Fizz')
  const buzz = optional(isBuzz, n).map(_ => 'Buzz')
  const num = optional(isNeither, n).map(String)
  return `${fizz.join('')}${buzz.join('')}${num.join('')}`
}
Thread Thread
 
kallmanation profile image
Nathan Kallman

Very nice! I think you have met the hardcore requirements.

And I think slightly less code than my functional solution will be, well done!