Created
August 14, 2011 10:39
-
-
Save plagelao/1144782 to your computer and use it in GitHub Desktop.
fizzbuzz FP style
This file contains 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
def fizzbuzz_strings | |
fizz = ->(number) { 'fizz' } | |
buzz = ->(number) { 'buzz' } | |
default = ->(number) { number.to_s } | |
[fizz, buzz, default] | |
end | |
def fizzbuzz_rules | |
multiple_of_3 = ->(number) { number % 3 == 0 } | |
multiple_of_5 = ->(number) { number % 5 == 0 } | |
criterias = [multiple_of_3, multiple_of_5] | |
default = ->(number) { not criterias.any?{|c| c.(number)} } | |
[multiple_of_3, multiple_of_5, default] | |
end | |
def fizzbuzz_strategy | |
fizzbuzz_rules.zip(fizzbuzz_strings) | |
end | |
def strings_for(number) | |
fizzbuzz_strategy.select{|criteria_for, _| criteria_for.(number)}. | |
map{|_, string_for| string_for.(number)} | |
end | |
def fizzbuzz(number) | |
strings_for(number).join | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment