-2

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.

  • I don't think it has a specific name. They're indexing into a sparse array, using modulo to repeat the same pattern every 15 numbers. – jonrsharpe Jun 26 '18 at 21:14
  • The FizzBuzz sequence repeats every 15 elements. The modulo operator `%` take advantage of that. The empty array elements become `undefined` in the array which is falsey so the the value of `i` can be used as a fallback. – Doug Coburn Jun 26 '18 at 21:14

1 Answers1

0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for answering it, I just want to understand this part, what does the , , between the numbers means? –  Aug 03 '18 at 19:03
  • 1
    Those are array elements that aren't filled in. `[, , 'fizz']` is similar to `[undefined, undefined, 'fizz']` – Barmar Aug 04 '18 at 05:27
  • Awesome! Now everything makes perfect sense! thank you so much. –  Aug 04 '18 at 06:35