DEV Community

loading...

Discussion on: Unconditional Challenge: FizzBuzz without `if`

Collapse
kallmanation profile image
Nathan Kallman Author • Edited

As promised, here is my functional approach to solving this (deeper article on it to come soon)

const functionalTrue = (onTrue, onFalse) => onTrue;
const functionalFalse = (onTrue, onFalse) => onFalse;
const isDivisible = (dividend, divisor) => [functionalTrue, ...Array(divisor).fill(functionalFalse)][dividend % divisor];

const functionalFizzBuzz = (n) => {
  const divisible_by_three = isDivisible(n, 3);
  const divisible_by_five = isDivisible(n, 5);
  return divisible_by_three(divisible_by_five("FizzBuzz", "Fizz"), divisible_by_five("Buzz", n));
};

Similar to Heiker's solution above; the main part of this solution is defining "true" and "false" as functions taking the same two parameters but returning one or the other.

Forem Open with the Forem app