...And The Good, Spoiler... Solved My Way


#1


im not sure of the proper grammar in my code. would appreciate any clean up you guys can find. thank you much...


var numbers = [1, 2, 3, 4 , 5, 6 , 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

for (var i=0; i < numbers.length; i++) {
    if(numbers[i] % 3 === 0 && numbers[i] % 5 === 0) {
        console.log("FizzBuzz");
    } else if (numbers[i] % 3 === 0){
        console.log("Fizz");
    }
      else if (numbers[i] % 5 === 0){
        console.log("Buzz")
      }
    else{
        console.log(numbers[i]);
    }
};


#2

One way to clean up is to remove literals. There is no real need to have an array since it comprises a sequence (ascending order, equal difference between terms). We can generate a sequence of any length within the for loop.

for (var i = 1; i < 21; i++) {
    if (i % 3 === 0 and i % 5 === 0) {

    }
    // ...
}

For greater simplicity we could use the LCM of 3 and 5, 15, in place of the logical expression:

if (i % 15 === 0) {
    // FizzBuzz
}

We could make a re-usable function that takes an upper limit which would be used in place of 21 in the above loop. Don't try that for this exercise, though. The SCT does not know to look for a function.

There are other methods we can try if you wish to have some more practice. Ternary expression and switch statement come to mind.

for (var i = 1, s; i < 21; i++) {
    s = "";
    s += i % 3 === 0 ? "Fizz" : "";
    s += i % 5 === 0 ? "Buzz" : "";
    console.log(s || i);
}

Revised after reading @jacobsandersen's post below.

console.log(s ? s : i);

equivalent of,

console.log(s || i);

#3

To go along, how about this @mtf? :wink:

for(i=1;i<21;++i)console.log(((i%3===0)?"Fizz":"")+((i%5===0)?"Buzz":"")||i);

To explain:

  1. Start a for loop at 1 until 20 using i as increment variable.
  2. For each iteration, increment i.
  3. For each iteration, check if i is cleanly divisible by 3. If so, add Fizz to the log.
  4. Also, for each iteration, check if i is cleanly divisible by '5'. If so, append Buzz to the previous message.
  5. If neither are correct, append i to the log using the || operator.

And, you can even make it a function:

var result = function(upper) { for(i=1;i<=upper;++i)console.log(((i%3===0)?"Fizz":"")+((i%5===0)?"Buzz":"")||i); }
result(10);
result(15);
result(20);

#4

Great one-liner. refactored some more...

(function(x){var i=0;while(i++ <x){console.log((i%3?"":"Fizz")+(i%5?"":"Buzz")||i);}})(20);

Of course this is just silliness, now.

Expanded...

(function(x) {
    var i = 0;
    while (i++ < x) {
        console.log((i % 3 ? "" : "Fizz") + (i % 5 ? "" : "Buzz") || i);
    }
})(20);

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.