DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

Here's a solution I like very much, because it uses function composition:

// helpers
const range = (m, n) => Array.from(Array(n - m + 1).keys()).map(n => n + m);
const compose = (fn1, ...fns) => fns.reduce((prevFn, nextFn) => value => prevFn(nextFn(value)), fn1);
const isDivisibleBy = divider => replacer => value => value % divider === 0 ? replacer : value;

// fizzbuzz definition
const fizz = isDivisibleBy(3)("Fizz");
const buzz = isDivisibleBy(5)("Buzz");
const fizzBuzz = isDivisibleBy(15)("FizzBuzz");

// this is what I like most about this implementation
const magic = compose(fizz, buzz, fizzBuzz);

console.log(range(1, 100).map(magic));

It's heavily inspired by tokdaniel's gist.