Project

General

Profile

each_uniq.rb

Hanmac (Hans Mackowiak), 04/23/2015 07:37 AM

 
1
module Enumerable
2
  def each_uniq(&block)
3
    return to_enum :each_uniq unless block_given?
4
    uniq_map = {}
5
    each do |*a|
6
      next if uniq_map.key?(a)
7
      uniq_map[a] = true
8
      block.call(*a)
9
    end
10
  end
11

    
12
  # @return [Enumerator]
13
  def each_uniq_by(&filter)
14
    Enumerator.new do |y|
15
      uniq_map = {}
16
      each do |*a|
17
        key = filter.call(*a)
18
        next if uniq_map.key?(key)
19
        uniq_map[key] = true
20
        y.yield(*a)
21
      end
22
    end
23
  end
24
end
25

    
26
src = [1, 1, 1, 1, 2, 2, 3, 4, 5, 6]
27
result = src.each_uniq.to_a
28

    
29
fail 'Dafuq happened there m8.' unless [1, 2, 3, 4, 5, 6] == result
30
result = src.each_uniq_by(&:even?).to_a
31

    
32
# actually I have no clue how to test this :x
33
fail 'each_uniq_by failed, epicly ;3' unless [1, 2] == result
34
result = src.each_uniq_by do |i|
35
  i * i
36
end.to_a
37
puts result.to_a