Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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