Skip to content

Instantly share code, notes, and snippets.

@IceDragon200
Last active August 29, 2015 14:19
Show Gist options
  • Save IceDragon200/5b1c205b4b38665c308e to your computer and use it in GitHub Desktop.
Save IceDragon200/5b1c205b4b38665c308e to your computer and use it in GitHub Desktop.
module Enumerable
def each_uniq(&block)
return to_enum :each_uniq unless block_given?
uniq_map = {}
each do |*a|
next if uniq_map.key?(a)
uniq_map[a] = true
block.call(*a)
end
end
# @return [Enumerator]
def each_uniq_by(&filter)
Enumerator.new do |y|
uniq_map = {}
each do |*a|
key = filter.call(*a)
next if uniq_map.key?(key)
uniq_map[key] = true
y.yield(*a)
end
end
end
end
src = [1, 1, 1, 1, 2, 2, 3, 4, 5, 6]
result = src.each_uniq.to_a
fail 'Dafuq happened there m8.' unless [1, 2, 3, 4, 5, 6] == result
result = src.each_uniq_by(&:even?).to_a
# actually I have no clue how to test this :x
fail 'each_uniq_by failed, epicly ;3' unless [1, 2] == result
result = src.each_uniq_by do |i|
i * i
end.to_a
puts result.to_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment