Skip to content

Instantly share code, notes, and snippets.

@DLMousey
Created July 31, 2017 23:49
Show Gist options
  • Save DLMousey/e0b6463ba955391c120f01be59a08fb5 to your computer and use it in GitHub Desktop.
Save DLMousey/e0b6463ba955391c120f01be59a08fb5 to your computer and use it in GitHub Desktop.
My attempt at the classic FizzBuzz interview question
/**
* @author Tom "DLMousey" <tom@llamatorials.com> (@DLMousey)
*/
/**
* Array of objects used as input for the calcualteFizzBuzz method.
* Interviewer wants it to work with 7s? Don't even bother modifying
* the code just add it here!
*/
var input = [
{
number: 3,
concat: "Fizz"
},
{
number: 5,
concat: "Buzz"
}
];
for(i = 1; i <= 100; i++) {
/**
* Create a new variable called output and assign it
* to the result of the calculateFizzBuzz() method.
*/
var output = calculateFizzBuzz(input, i);
/**
* If the method returned something falsy (in this case an empty string),
* We'll re-assign the outpu to whichever number we're currently on
*/
if(!output) {
output = i;
}
/**
* Print the contents of the output variable and some new lines because
* we're super fancy like that.
*/
console.log(output + "\n\n");
}
/**
* Takes an array of objects, iterates through them to determine
* whether they fit the "FizzBuzz" pattern
*
* @param {array} inputs
* @param {int} currentIteration
*/
function calculateFizzBuzz(inputs, currentIteration) {
/**
* Another Output variable, But we're within the scope
* of another method so this won't affect the one defined above
* until we return it, Which is then used as the value for the
* Output variable above
*/
var output = "";
/**
* Iterate over the properties in the inputs object, Figure out whether the
* current iteration (i, from above) is divisible by the number we're currently
* looking at inside the inputs object.
*
* If it is divisible, Tag on the string defined in the Input's "Concat" property
* (Called Concat because we'll Concatenate it onto the output if the conditions are met)
*/
Object.keys(inputs).map(function(objectKey, index) {
if(currentIteration % inputs[objectKey].number == 0) {
output += inputs[objectKey].concat
}
});
/**
* Send back the seperate "Output" variable we constructed down here
*/
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment