Storing data inside an object, inside an array is extraneous, when you're using key values for everything.
Try this kind of data structure instead:
var fizzBuzzContent = {
"3": "Badger",
"5": "Mushroom",
"15": "Ooohhh it's a snaaaakkkeeee"
}
And instead of implicitly storing this layout inside the function, let's make it dynamic and add the 'options' as a parameter, defaulting to the original FizzBuzz if you don't provide your own options. Additionally defaulting to the original 30
limit from the question.
options = options || {
3: "Fizz",
5: "Buzz",
15: "FizzBuzz"
};
limit = limit || 30;
this.calculate
: It's not really an accurate name, there's not a 'calculation' done, you just start the FizzBuzz process.
counter
: Really just i
or index
works fine.
forEach
: Some people aren't particularly a fan of forEach
and if your build's target audience can't support ES5, then you either need to use a polyfill or something else.
Personally, I'm an advocate of forEach
.
As it's a prototype of Array
, you can't directly use objects.
But you just suggested an object...
Object
has a handy function on it that gets all the keys in the object as an array. By traversing this, you can use the first parameter only in forEach
:
Object.keys(options).forEach(function(key){
...
}
line = counter.toString()
: This is JavaScript, making a variable stay in the same type is not a feature of the language, you needn't worry if line
becomes an integer, it won't cause issues.
Instead of assigning line
you could just use a ternary statement return
/console.log
instead:
console.log(
index % key === 0
? options[key]
: index
);
Putting that together:
function FizzBuzz(limit, options){
limit = limit || 30;
options = options || {
3: "Fizz",
5: "Buzz",
15: "FizzBuzz"
};
this.startLoop = function(){
for(var index = 1; index <= limit; index++) {
Object.keys(options).forEach(function(key){
console.log(
index % key === 0
? options[key]
: index
);
});
}
}
}
var badgersSongOptions = {
3: "Badger",
5: "Mushroom",
15: "Ooohhh it's a snaaaakkkeeee"
};
var limit = 100;
var BadgersSong = new FizzBuzz(limit, badgersSongOptions);
BadgersSong.startLoop();