Sha256: a6427a7d41ba69ffe4b0116a73e234cc31f2c989f60381d1975723b06673d4fd

Contents?: true

Size: 1.56 KB

Versions: 8

Compression:

Stored size: 1.56 KB

Contents

require_relative 'divide_by_type'
require_relative 'amount'

class Aggregator
  def self.aggregate(&block)
    agregator = Aggregator.new
    block.call(agregator)
    return Amount.new(agregator.total,agregator.total_by_type)
  end

  def self.aggregate_full_precistion(&block)
    agregator = Aggregator.new
    block.call(agregator)
    return Amount.new(agregator.total,agregator.total_by_type)
  end

  def add(amount)
    total_list << Aggregator.prepare(amount)
  end

  def add_full_precision(amount)
    raise "Full precision can be done only on amount class. Class sended was: #{amount.class} with value: #{amount.inspect}" if amount.class != Amount
    total_list << amount.by_type
  end

  def subtract(amount)
    add(amount.negative)
  end

  def subtract_full_precision(amount)
    add_full_precision(amount.negative)
  end

  def total
    (by_type? ? total_by_type : total_list).sum_me
  end

  def total_by_type
    Aggregator.agregate_by_type(total_list)
  end

  private

  def by_type?
    return false if @total_list == []

    total_list[0].class == Hash
  end

  def total_list
    @total_list ||= []
  end

  #hey don't judge me, yes I know I am a bad man
  def self.agregate_by_type(lista)
   return {} if lista[0].class != Hash

   result = lista.inject { |memo, el| self.merge_by_key(memo, el) }
   (result.nil? ? {} : result).reject { |key, value| value == 0 }
  end

  def self.merge_by_key(memo, el)
    memo.merge( el ) { |key, old_v, new_v| old_v + new_v }
  end

  def self.prepare(amount)
    amount.class == Amount ? amount.divide : amount
  end
end #Agregator

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
guerrilla_patch-3.0.3 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-3.0.2 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-2.8.7 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-2.8.6 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-2.8.5 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-2.8.4 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-2.8.3 lib/guerrilla_patch/aggregate_by_type/aggregator.rb
guerrilla_patch-2.8.2 lib/guerrilla_patch/aggregate_by_type/aggregator.rb