Skip to content

Instantly share code, notes, and snippets.

@robinpokorny
Last active November 1, 2016 09:42
Show Gist options
  • Save robinpokorny/c60ea7a5cf598632a53346393322ea3e to your computer and use it in GitHub Desktop.
Save robinpokorny/c60ea7a5cf598632a53346393322ea3e to your computer and use it in GitHub Desktop.
Minimal readable Fizz Buzz test solution in JavaScript
// This function isolates the logic
// Its param is number `i`
// It returns 'Fizz', 'Bazz', 'FizzBuzz' or the number
// (This implementation takes advatage of some JavaScript specific features)
const toFizzBuzz = (i) =>
// We construct a string
// First part is 'Fizz' if the number is divisible by 3
// and an empty string otherwise
// `i%3` is 0 iff `i` is divisible by 3
// 0 is a falsy value
// condition ? truthy (= here other than 0) : falsy (= here 0)
(i%3 ? '' : 'Fizz')
// Second part is 'Buzz' if the number is divisible by 5
// and an empty string otherwise
+ (i%5 ? '' : 'Buzz')
// The constructed string is either
// 1) Non-empty: The number is divisible by 3, 5, or both.
// We want to return the string
// 2) Empty: The number is not divisible by 3 or 5
// We want to return the number `i`
// The logical OR (||) operator
// returns the expresion before `||` if this expression is truthy
// otherwise returns the expression after `||`.
// Empty string is falsy value, non-empty string is truthy
|| i
// Create an array of 100 items
Array(100)
// Convert to a dense array so we can iterate it with `map` and `forEach`
.fill()
// The array is now a hundred times `undefined`,
// Turn it into a sequence 0..99 by taking the position of an element `i`
// Also shift by one so the result is 1..100
.map((_, i) => i + 1)
// Transform to FizzBuzz
.map(toFizzBuzz)
// Write each item to the output
.forEach((i) => console.log(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment