Class: Enumerating::Prefetcher

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/enumerating/prefetching.rb

Instance Method Summary collapse

Methods included from Enumerable

#[], #collecting, #dropping, #dropping_while, #prefetching, #rejecting, #selecting, #taking, #taking_while, #threading, #uniqing, #uniqing_by

Constructor Details

#initialize(source, buffer_size) ⇒ Prefetcher

Returns a new instance of Prefetcher.



7
8
9
10
# File 'lib/enumerating/prefetching.rb', line 7

def initialize(source, buffer_size)
  @source = source.to_enum
  @buffer_size = buffer_size
end

Instance Method Details

#each(&block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/enumerating/prefetching.rb', line 12

def each(&block)
  return @source.each(&block) if @buffer_size <= 0
  buffered_elements = []
  i = 0
  @source.each do |element|
    slot = i % @buffer_size
    if i >= @buffer_size
      yield buffered_elements[slot]
    end
    buffered_elements[slot] = element
    i += 1
  end
  buffered_elements.size.times do
    slot = i % buffered_elements.size
    yield buffered_elements[slot]
    i += 1
  end
end