Last active
November 14, 2015 23:15
-
-
Save 0xadada/ccb5cd069138e5bb7549 to your computer and use it in GitHub Desktop.
FizzBuzz Javascript Solution - Bodyless for loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Concise | |
var f='Fizz', b='Buzz', i=0, d3, d5; | |
for (i; ++i <= 100; d3 = !(i % 3), d5 = !(i % 5), console.log(d3 ? d5 ? f+b : f : d5 ? b : i)); | |
// Multi-line, commented | |
var /* Declare our variables outside the loop, a performance best-practice */ | |
f='Fizz', /* Variable `f` so we don't repeat 'Fizz' twice - DRY */ | |
b='Buzz', /* Variable `b` so we don't repeat 'Buzz' twice - DRY */ | |
i=0, /* For-loop counter, start at 0 */ | |
d3, /* setup a variable for checking divisibility by 3 */ | |
d5; /* setup a variable for checking divisibility by 5 */ | |
for ( /* Bodyless for loop */ | |
i; /* Iterator on i */ | |
++i <= 100; /* ++i pre-increments to 1, stops at 100 */ | |
d3 = !(i % 3), /* Logically we're testing for i%3 === 0 to be TRUE, indicating | |
* i is divisible by 3. Instead we test for 0, which also | |
* represents FALSE in Javascript. Use the ! NOT operator | |
* to coerce 0 to boolean value 1- which is TRUE. */ | |
d5 = !(i % 5), /* Testing that NOT (i % 5) is TRUE using same logic as above */ | |
console.log( /* ouput the result of a ternary operation to the console */ | |
d3 ? /* was i divisible by 3? */ | |
d5 ? /* was i divisible by 5? *? */ | |
f+b : /* Both conditions d3 and d5 are divisible TRUE: return string 'FizzBuzz': else */ | |
f : /* only !(i%3) is true, just return string 'Fizz' */ | |
d5 ? /* BOTH 3 AND 5 weren't divisible, was 5 divisible by itself TRUE? */ | |
b : /* yes, return 'Buzz' */ | |
i /* Nope, just return i */ | |
) /* end of console.log */ | |
); /* end of for-loop */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment