# require "eitil_integrate/application_exporter/auto_sum/sum_data" module EitilIntegrate::RubyXL module AutoSum class << self # Reduce values and alter data structure. def sum_data sum_floats sum_time_strings unpack_arrays end def sum_floats @hash.transform_values! { |array| float_array?(array) ? [array.sum] : array } end def sum_time_strings @hash.transform_values! { |array| time_string_array?(array) ? chronic_sum_array(array) : array } end def chronic_sum_array(array) #total minutes, hours and days tm, th, td = [0]*3 array.each do |time_string| # add empty 0's, to avoid defining nil values when time values are absent h, m, s = *time_string.split(':').map(&:to_i), *[0]*3 tm += m; th += h end # parsing times into maxes (60 m, 24 h, ∞ days) th += tm / 60 tm = tm % 60 td += th / 24 th = th % 24 # formatting strings sd = td.to_s sh = th.to_s.rjust(2,'0') sm = tm.to_s.rjust(2,'0') [[sd, sh, sm].join(':')] end def format_time(time) time.to_s.length == 1 ? "0#{time}" : time.to_s end def float_array?(array) return false if array.empty? array.all? { |item| item.is_a?(Float) } end def time_string_array?(array) return false if array.empty? array.all? { |item| item.is_a?(String) && item.scan(/\d{2}:\d{2}:\d{2}/) } end def unpack_arrays @hash.transform_values! { |array| array.empty? ? nil : array.first } end end end end