FizzBuzz in JavaScript

Functions are first class objects. Functions establish closures.

Problem: Given a range of positive, non-zero integers, output “Fizz” if the number is evenly divisible by 3, output “Buzz” is the number is evenly divisible by 5, and output “FizzBuzz” if the number is evenly divisible by both 3 and 5; otherwise, output the number.

divisor = function(number, string) {
  return(function(d) {
    if (d % number === 0) {return(string)} else {return("")};
  });
}

mod3er = divisor(3, "Fizz");
mod5er = divisor(5, "Buzz");

for(i = 1; i <= 100; i = i + 1) {
    res = mod3er(i) + mod5er(i);
    console.log(res === "" ? i : res);
}

Leave a Reply

Your email address will not be published. Required fields are marked *