Alright, here's my solution: https://jsfiddle.net/jf68mfj1/2/
I went for some solutions that may not be "good coding practices" depending on who you ask, because I wanted to explore JavaScript a bit further than a basic for-loop and if-statement.
Here's the main fizzBuzz function:
function fizzBuzz(num) {
let returnValue = '';
if (num % 3 === 0) returnValue += 'Fizz';
if (num % 5 === 0) returnValue += 'Buzz';
return returnValue || String(num);
}
Like others I concatenate Fizz
and Buzz
so I don't need a third if-statement. As a bonus I use JavaScript's type coercion to check if returnValue is truthy, and if it's not (an empty string ''
is falsy) I return the original number. Initially I returned it as an integer too, but returning mixed types is bad practice and in fact actually broke my tests, so I return it a as string now too.
Fizzing from 0 to 100 I do with this method:
function fizzTo100() {
const allFizzBuzzes = [...Array(100).keys()].map(fizzBuzz);
output(allFizzBuzzes.join('\n'));
}
The first line looks a bit like a hack. What I do is create an array of 100 length and then take the keys from that array. All the values are still undefined, but the keys are 0-100. The result of keys()
is an iterable though, so I turn it back into an array using the spread operator in a new array [...x]
.
Now I have an array of 1-100 that I can map to fizzBuzz.
See and test my code here: https://jsfiddle.net/jf68mfj1/2/
If anyone is interested in more details let me know and I'll write a blog post about it. Not going throught that effort if nobody cares though ;)
This is really neat. Well done
+1 for
and for having a test that breaks when this is not the case, tip! worthy :)
The
||
is a pretty clean way, I like that!Your explanation on why you used the spread operator is glorious! Thank you for giving insight into why you used that :)
I would definitely read a blog post about it. But if you want to save your efforts for a harder challenge, a new one will come up pretty soon :)
Thanks! In that case I'll wait for the next one. This is fun :)
Hi @pilcrow! You have just received a 0.5 SBD tip from @reggaemuffin!
@tipU quick guide | How to check your pending payouts.