CLEAN CODE: THE FIZZ BUZZ TEST

By: Saurav

2017-11-24 06:20:00 UTC

Given a positive integer N, print all the integers from 1 to N. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. Also for number which are multiple of 3 and 5, prints “FizzBuzz”.

Example

N = 5
Return: [1 2 Fizz 4 Buzz]

InterviewBit

We should start by writing a simple function which returns fizz buzz accordingly but lets start by writing tests first

p get_appropriate_return_value(1) == 1 
p get_appropriate_return_value(3) == "Fizz"
p get_appropriate_return_value(5) == "Buzz"
p get_appropriate_return_value(15) == "FizzBuzz"
p get_appropriate_return_value(9) == "Fizz"
p get_appropriate_return_value(45) == "FizzBuzz"
p get_appropriate_return_value(25) == "Buzz"

def get_appropriate_return_value(input_number)
  return "FizzBuzz" if input_number%15 == 0
  return "Buzz" if input_number%5 == 0
  return "Fizz" if input_number%3 == 0
  return input_number
end

Lets write some tests for the method which iterates through the array and print out the results

p fizzBuzz(1) == [1]
p fizzBuzz(2) == [1,2]
p fizzBuzz(3) == [1,2,"Fizz"]
p fizzBuzz(5) == [1,2,"Fizz", 4, "Buzz"]
p fizzBuzz(15) == [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
p fizzBuzz(9) == [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz"]
 p fizzBuzz(45) == [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz"]
p fizzBuzz(25) == [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz"]

def fizzBuzz(input_number, output_array = Array.new)
  return output_array if input_number < 1
  
  (1..input_number).each do |i|
    output_array << get_appropriate_return_value(i)
  end
  
  return output_array

end

Not the best looking code is it!

Lets try refactoring a little.

Attempt 2:

def fizzBuzz(input_number)
   input_number < 1 ? [] : generate_fizzbuzz_array(input_number)
end

def generate_fizzbuzz_array(input_number)
  return (1..input_number).to_a.map { |i| get_appropriate_return_value(i) }
end 


def get_appropriate_return_value(input_number)
  return "FizzBuzz" if input_number%15 == 0
  return "Buzz" if input_number%5 == 0
  return "Fizz" if input_number%3 == 0
  return input_number
end 


Let me know what you think!
Twitter: sprakash24oct
Linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)