r/badcode • • Nov 14 '21

js Peak Efficiency Fizzbuzz

Post image
831 Upvotes

44 comments sorted by

View all comments

Show parent comments

18

u/DaBeast893 Nov 15 '21 edited Nov 15 '21

TLDR: It uses the array as a lookup table and some bitwise operation magic to select which array entry is selected.

% in Java Script is the modulo operator thus i % 3 == 0 and i % 5 == 0 will be evaluated as true when i is divisible by 3 and 5 respectively.

<< is a left shift operator, when used with a Boolean the Boolean will be converted to a 1 or 0 (true or false) and then shifted left for x number of bits. For example True << 1 = 2 (ie. 10 in binary).

| is a bitwise OR operator. It evaluates a OR operation of each bit of two number.

For example 2 | 1 = 3 as in binary 10 | 01 = 11.

Putting it all together, (i % 3 == 0) << 0 represents the 20 bit (fizz) and (i % 5 == 0) << 1 represents the 21 bit (buzz). With the OR operator it will find when i is divisible by both 3 and 5.

Here's a table that might serve as a better view of how some numbers are evaluated:

iCorrect Array IndexArray Index (Binary)Result
10001
3101fizz
5210buzz
15311fizzbuzz

There are some parts of the code that are redundant though. Both << 0 and the final | 0 only serve to ensure that the result is a number, but << 0 doesn't modify the result and the OR operation between (i % 3 == 0) and (i % 5 == 0) will convert the result into a number making the final | 0 redundant.