Skip to content

Instantly share code, notes, and snippets.

@JamesAlias
Last active March 17, 2016 13:42
Show Gist options
  • Save JamesAlias/803db61c646b389096d8 to your computer and use it in GitHub Desktop.
Save JamesAlias/803db61c646b389096d8 to your computer and use it in GitHub Desktop.
A FizzBuzz implementation in JS/ES6. It could be a lot smaller and 'smarter' but it aims to be readable and understandable at the first glance. I also like the reusability.
/**
* FizzBuzz for a single value.
* @param {number} number - The value to be tested.
* @returns {number | string} - The same Number or 'Fizz', 'Buzz', 'FizzBuzz'.
*/
function fizzBuzz(number = 0) {
if (number === 0) {
return 0;
}
let word = '';
if (number % 3 === 0) {
word = 'Fizz';
}
if (number % 5 === 0) {
word += 'Buzz';
}
return (word.length > 0) ? word : number;
}
/**
* FizzBuzz over a numerical range.
* @param {number} a - First range parameter.
* @param {number} b - Optional second range parameter. Default = 0.
* @returns {array} - An array of all 'FizzBuzzed' values in given range.
*/
function fizzBuzzFromRange(a, b = 0) {
let min = Math.min(a, b);
let max = Math.max(a, b);
let it = [];
for (let i = min; i <= max; i++) {
it.push(fizzBuzz(i));
}
return it;
}
/**
* FizzBuzz over all values of an array.
* @param {array} arr - The input array. Default = [] (empty array).
* @returns {array} - The 'FizzBuzzed' array.
*/
function fizzBuzzFromArray(arr = []) {
return arr.map((number) => fizzBuzz(number));
}
// usage examples
console.log(fizzBuzz(15));
fizzBuzzFromRange(100).forEach((value) => console.log(value));
console.log(fizzBuzzFromRange(100).filter(value => value === 'FizzBuzz').length);
fizzBuzzFromRange(-50, 50).forEach((value) => console.log(value));
let numbers = [];
for (let i = 1; i <= 15; i++) {
numbers.push(i);
}
fizzBuzzFromArray(numbers).forEach((value) => console.log(value));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment