Last active
February 13, 2017 04:53
-
-
Save knicklabs/17a5a08c6d03b623afb32409d893ee68 to your computer and use it in GitHub Desktop.
Even more ridiculous abstraction for fizzbuzz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const maybe = (result) => { | |
return { | |
if(number) { | |
return { | |
divisibleBy(divisor) { | |
return number % divisor === 0 && result; | |
} | |
} | |
} | |
} | |
} | |
const resultFor = (number) => { | |
return { | |
using(rules) { | |
let result | |
try { | |
rules.forEach((output, divisor) => { | |
result = maybe(output).if(number).divisibleBy(divisor) | |
if (result) throw rules | |
}) | |
} catch (error) { | |
if (error !== rules) { | |
throw error | |
} | |
} | |
return result || number | |
} | |
} | |
} | |
const fizzBuzz = (min, max) => { | |
const numbers = Array.from({length: max + 1}).map((_, index) => index).slice(min); | |
const rules = new Map([ | |
[15, 'FizzBuzz'], | |
[5, 'Buzz'], | |
[3, 'Fizz'] | |
]) | |
return numbers.map((number) => resultFor(number).using(rules)) | |
} | |
const results = fizzBuzz(1, 100) | |
console.log(results.join('\n')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment