Skip to main content
2 of 6
deleted 1 character in body
Joseph
  • 25.2k
  • 2
  • 25
  • 37

First, isLt100, isDivBy3 and your other functions are vaguely named. Better name them fully and meaningfully. There's no harm done with the extra keystrokes in the name.

Also, you would want to make your range flexible. Now, as far as I know, functional programming fans prefer a "range" function to iterate through. Since there's no such thing in JS, this SO answer provides us one. It's essentially just creating an array of n length.

Next is your fizzbuzz. Since we have an array of numbers thanks to range, all we need to do now is just replace those with numbers, fizz, buzz or fizz buzz. We can use the native map array method to do that.

Your other functions are a bit verbose, so I just collapsed them into a simple ternary. I kept the division functions because they were used more than once.

function range(n){
  return Array.apply(null, Array(n)).map(function (_, i) {return i;});
}

function isDivisibleByThree(n){
  return n % 3 === 0;
}

function isDivisibleByFive(n){
  return n % 5 === 0;
}

function fizzBuzzTest(n){
  // Since these are called at least once (during the "fizz buzz"), we don't
  // want to call them again when it fails "fizz buzz", so we cache.
  var by3 = isDivisibleByThree(n);
  var by5 = isDivisibleByFive(n);

  return  by3 && by5 ? 'fizz buzz'
               : by3 ? 'fizz'
               : by5 ? 'buzz'
                     : n;
}

function fizzBuzz(n){
  return range(n).map(x => fizzBuzzTest(x + 1)).join(', ');

  // A non-OOP approach would have the same, except function calls are nested rather
  // than chained (Python)
  // return ','.join(map(lambda x: fizzBuzz(x + 1), range(100)));
}

document.write(fizzBuzz(100));

Joseph
  • 25.2k
  • 2
  • 25
  • 37