Class: MovingAvg::Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/moving_avg/helper.rb

Class Method Summary collapse

Class Method Details

.build_with_sliding(items:, window_size:, strategy:) ⇒ Object

repeatedly calculate moving average separating items by window size. the first N-1 items should be padded or calculated from inconvinient data



8
9
10
11
12
13
14
15
# File 'lib/moving_avg/helper.rb', line 8

def build_with_sliding(items:, window_size:, strategy:)
  map_with_sliding(
    items: items,
    window_size: window_size,
  ).map { |data|
    MovingAvg::Base.public_send(strategy, data)
  }
end

.map_with_sliding(items:, window_size:) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/moving_avg/helper.rb', line 17

def map_with_sliding(items:, window_size:)
  items.each_with_object([]) { |val, acc|
    if acc.last.nil?
      # the first time
      acc << [val]
    elsif acc.last.size < window_size
      # the first window
      acc.last << val
    else
      # the following windows
      next_window = acc.last.dup
      next_window.shift
      next_window << val
      acc << next_window
    end
  }
end