Skip to content

Instantly share code, notes, and snippets.

@kevinchappell
Created February 17, 2017 16:39
Show Gist options
  • Save kevinchappell/5a932e909cd5c41f12a624cad66c6d78 to your computer and use it in GitHub Desktop.
Save kevinchappell/5a932e909cd5c41f12a624cad66c6d78 to your computer and use it in GitHub Desktop.
Configurable FizzBuzz
// Tired of seeing if else if else if else in fizzbuzz exercise I created
// this configurable FizzBuzz that uses only one if statement.
// https://jsfiddle.net/kevinchappell/44jrznbj/
/**
* Configurable fizzBuzz
* @param {Object} args
* @param {Number} until number of iterations
* @return {String} output
*/
function fizzBuzz(args, until) {
var keys = Object.keys(args),
argsLength = keys.length,
output = [];
until = until + 1;
for (var i = 1; i < until; i++) {
var values = [];
for (var x = 0; x < argsLength; x++) {
var key = parseInt(keys[x]);
if (i % key === 0) {
values.push(args[key]);
}
}
output.push(i + ': ' + values.join(' '));
}
return output.join('\n');
}
// Usage:
// define and config object for your fizzbuzz where the key is
// the number of iterations to make before outputting the value
// key is multiple, value is output
var args = {
3: "Fizz",
5: "Buzz"
};
console.log(fizzBuzz(args, 15));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment