Method: Laziest::Group#initialize

Defined in:
lib/laziest/group.rb

#initialize(enumerator, &block) ⇒ Group



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/laziest/group.rb', line 5

def initialize enumerator, &block
  @hash = {}
  @lazy_arrays = {}
  @buffers = ::Hash.new{|h,k|h[k]=[]}
  @enumerator = enumerator
  @group_block = block
  @enum_mutex = ::Mutex.new
  super() do
    # Any existing lazy arrays can simply be forced, since
    # they're on a different mutex now:
    @lazy_arrays.each do |arr|
      arr.__force__
    end
    # And just in case there aren't any lazy arrays:
    ::Kernel.loop do
      val = enumerator.next
      key = yield val
      (@hash[key] ||= []) << val
    end
    # Strip out anything that turned out to be empty.
    @hash.delete_if {|k,v| v.empty?}
    # clear potentially-expensive GC-able stuff.
    @lazy_arrays = nil
    @buffers = nil
    @group_block = nil
    # safe because we already forced all existing lazy arrays, and we're
    # holding the global mutex which prevents any new ones from being built
    @enum_mutex = nil
    @hash
  end
end