Sha256: 4b51a07ff32c4ce7b158cf5e1647b88d0faaa08161e0f4302e175c4abfc05635

Contents?: true

Size: 986 Bytes

Versions: 3

Compression:

Stored size: 986 Bytes

Contents

module MovingAvg
  class Helper
    class << self
      # repeatedly calculate moving average
      # separating items by window size.
      # the first N-1 items should be padded
      # or calculated from inconvinient data
      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

      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
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
moving_avg-0.2.2 lib/moving_avg/helper.rb
moving_avg-0.2.1 lib/moving_avg/helper.rb
moving_avg-0.2.0 lib/moving_avg/helper.rb