Last active
May 20, 2018 14:28
-
-
Save ivandenysov/afdd38df10e1ca999c0af777695e36a1 to your computer and use it in GitHub Desktop.
Even Fibonacci Numbers
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
class FibonacciSequence | |
DEFAULT_MAX = 4_000_000 | |
DEFAULT_FILTER_BY = :even? | |
def initialize(max: DEFAULT_MAX, filter_by: DEFAULT_FILTER_BY) | |
@max = max | |
@filter_by = filter_by | |
validate_arguments | |
@enumerator = build_enumerator | |
end | |
def sum | |
to_a.reduce(&:+) | |
end | |
def to_a | |
@enumerator.to_a | |
end | |
private | |
def validate_arguments | |
raise(ArgumentError, "max must be a Numeric.") unless @max.is_a?(Numeric) | |
unless @filter_by.is_a?(String) || @filter_by.is_a?(Symbol) | |
raise(ArgumentError, "filter_by must be a String or a Symbol.") | |
end | |
end | |
def build_enumerator | |
Enumerator.new do |yielder| | |
previous = 1 | |
following = 2 | |
yielder << previous if previous.send(@filter_by) | |
yielder << following if following.send(@filter_by) | |
loop do | |
previous, following = following, previous + following | |
next unless following.send(@filter_by) | |
break if following > @max | |
yielder << following | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment