Created
September 29, 2014 23:33
-
-
Save ldanz/3658322c76afb9c06653 to your computer and use it in GitHub Desktop.
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
module FakeEnumerable | |
def map | |
res = [] | |
each do |item| | |
res << yield(item) | |
end | |
res | |
end | |
def select | |
res = [] | |
each do |item| | |
res << item if yield(item) | |
end | |
res | |
end | |
def sort_by(&block) | |
temp_array = [] | |
each do |item| | |
temp_array << [item, yield(item)] | |
end | |
temp_array.sort_by { |x, y| y }.map { |x, y| x } | |
end | |
def reduce(*args, &block) | |
initial_given = false | |
sym_given = false | |
acc, sym = case args.size | |
when 0 | |
raise LocalJumpError unless block_given? | |
[nil, nil] | |
when 1 | |
if block_given? | |
initial_given = true | |
[args.first, nil] | |
else | |
sym_given = true | |
[nil, args.first] | |
end | |
when 2 | |
initial_given = true | |
sym_given = true | |
args | |
end | |
transformation = ->(acc, elt) { acc.send(sym, elt) } if sym_given | |
first_pass = true | |
each do |item| | |
acc = | |
if first_pass && !initial_given | |
item | |
else | |
if sym_given | |
transformation.call(acc, item) | |
else | |
yield(acc, item) | |
end | |
end | |
first_pass = false | |
end | |
acc | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment