Last active
May 20, 2020 11:39
-
-
Save annikoff/2afd21c8c4c4a2b8a113655c05c1ee46 to your computer and use it in GitHub Desktop.
CustomEnumerable module
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
module CustomEnumerable | |
def map(sym = nil) | |
return enum_for(:map) if !block_given? && sym.nil? | |
raise SyntaxError if block_given? && !sym.nil? | |
result = [] | |
each do |item| | |
result << (sym.nil? ? yield(item) : item.send(sym)) | |
end | |
result | |
end | |
def find(sym = nil) | |
return enum_for(:find) if !block_given? && sym.nil? | |
raise SyntaxError if block_given? && !sym.nil? | |
each do |item| | |
return item if sym.nil? ? yield(item) : item.send(sym) | |
end | |
nil | |
end | |
def reduce(initial_or_sym, sym = nil) | |
if initial_or_sym.is_a?(Symbol) | |
operator = initial_or_sym | |
initial = nil | |
else | |
initial = initial_or_sym | |
operator = sym | |
end | |
accumulator = initial | |
each_with_index do |item, index| | |
if index.zero? && initial.nil? | |
accumulator = item | |
next | |
end | |
accumulator = operator.nil? ? yield(accumulator, item) : accumulator.send(operator, item) | |
end | |
accumulator | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment