Search code examples
javascriptfizzbuzz

Fizz Buzz question with extra difficulty layer


I am trying to solve the Fizz Buzz question with an extra layer.

This is what I have so far. All this works fine but I need one more extra condition.

It's JS Unit testing

For any other input (valid or otherwise) return a string representation of the input

printFizzBuzz = function(input) {

  // Your code goes here
  for (var i = 1; i <= 20; i++) {

    if (i % 3 === 0 && i % 5 === 0) {
      console.log("FizzBuzz");
    } else if (i % 3 === 0) {
      console.log("FizzBuzz");
    } else if (i % 5 === 0) {
      console.log("Buzz");
    } else {
      console.log(i);
    }
  }
};

Thank you!


Solution

  • Looking at the question, it is not asking for a loop, it is asking for any value passed to the function. So the answer should look more like this

    function printFizzBuzz(input) {
    
      // Your code goes here
    
      if (typeof input !== ‘number’) {
        return String(input)
      }
    
      let by3 = input % 3
      let by5 = input % 5
    
      switch(0) {
        case by3 + by5:
          return "FizzBuzz"
    
        case by3:
          return "Fizz"
    
        case by5:
          return "Buzz"
    
        default:
          return input.toString()
        }
      }
    }