FizzBuzz Test
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
—c2.com
Here’s my solution:
Test Driven Development Approach
// TDD Readable
var getFizzBuzzStatements = function (len) {
var arr = [],
str = "";
for (var i = 1; i <= len; i++) {
str = (i % 3) ? "" : "Fizz";
str += (i % 5) ? "" : "Buzz";
arr.push(str||i);
}
return arr;
};
var fizzBuzz = function () {
console.log(getFizzBuzzStatements(100).join("\n"));
};
fizzBuzz();
Alternative: One liner
// One liner
for (i = 1; i <= 100; i++)
console.log((((i % 3) ? "" : "Fizz") + (i % 5 ? "" : "Buzz")||i) + "\n")
Alternative: Switches
var getFizzBuzzStatements = function (len) {
var j,
arr = [];
for (var i = 1; i <= len; i++) {
switch (i % 15) {
case 0:
arr.push("FizzBuzz");
break;
case 3: case 6: case 9: case 12:
arr.push("Fizz");
break;
case 5: case 10:
arr.push("Buzz");
break;
default:
arr.push(i);
}
}
return arr;
};
var fizzBuzz = function () {
console.log(getFizzBuzzStatements(100).join("\n"));
};
Demo
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
I'd argue that the ternary operator is still an if statement.
Updated. I posted a solution using switches. :)
Hey there. You recently posted on another article this solution doesn't use if conditions. As far as I see, you are, but in the shorthand form. Am I missing something here?
You're right. So I updated my solution.