Last active
December 9, 2015 17:28
-
-
Save terraboops/4303806 to your computer and use it in GitHub Desktop.
JS FizzBuzz, Generalized
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
//Factory for Test Conditions | |
function testFactor(factor, msg) { | |
"use strict"; | |
return function(i){ | |
var output = ""; | |
if(i%factor===0) { | |
output = msg; | |
} | |
return output; | |
}; | |
} | |
//Takes an array of test conditions and a number to count to | |
//Returns array of result strings for each counted number | |
function fizzBuzz(tests, count){ | |
"use strict"; | |
var output = []; | |
var current = ""; | |
for(var i=1; i<=count; i++){ | |
current = ""; | |
for(var j=0;j<tests.length;j+ { | |
current += tests[j](i); //execute the tests in the test array. | |
} | |
if(current === ""){ | |
current = i; //if the tests returned nothing, then print the number | |
} | |
output.push(current); | |
} | |
return output; | |
} | |
(function() { | |
"use strict"; | |
var tests = [testFactor(3,"Fizz"), | |
testFactor(5,"Buzz")]; | |
//testFactor(n, "Woot!") | |
var count = 100; | |
var toPrint = fizzBuzz(tests,count); | |
var li; | |
for(var i=0; i<toPrint.length; i++){ | |
li = document.createElement('li'); | |
li.textContent = toPrint[i]; | |
document.getElementById('fizzList').appendChild(li); | |
} | |
})(); |
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
li { | |
list-style-type: none; | |
} | |
</style> | |
</head> | |
<body> | |
<ul id="fizzList"> | |
</ul> | |
<script src="fizzBuzz.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment