Search code examples
javascriptarraysfor-loopfizzbuzz

What is this way of resolving the Fizzbuzz challenged called?


I am new to programming, and I am currently doing the FizzBuzz test, it looks simple at first but we got some requirements to perform it:

  • I can use only one if. No multiple branches, ternary operators or else.
  • Unit tests.

I made it by using switch statements, but looking on the internet, I found this way which is shorter, but it is not clear how this process of solving the FizzBuzz challenge is.

This is the code:

var i, values = [, , 'fizz', , 'buzz', 'fizz', , , 'fizz', 'buzz', , 'fizz', , , 'fizzbuzz'];
for (i = 0; i < 100; console.log(values[i++ % 15] || i));

If anyone understands this way of solving the FizzBuzz challenge I would appreciate if it can be explained.


Solution

  • It's called a "lookup table". The pattern of responses cycles through all the possibilities every 15 numbers, because that's the least common multiple of 3 and 15. So we calculate the number modulo 15, and use that as the index into an array of all 15 possibilities.

    The blank elements in the array are used to print the numbers themselves instead of fizz or buzz. Leaving an array element is roughly equivalent to specifying undefined as the value, so this is just a shorter way of writing

    values = [undefined, undefined, 'fizz', undefined, 'buzz', 'fizz', undefined, undefined, 'fizz', 'buzz', undefined, 'fizz', undefined, undefined, 'fizzbuzz'];
    

    Since undefined is falsey, values[i++ % 15] || i will be i whenever the array element isn't filled in with one of the strings.