From 69f3431e7032fa6fa3811313effb37e7649ee85a Mon Sep 17 00:00:00 2001 From: Vitalii Chulak Date: Wed, 14 Feb 2024 10:26:31 +0200 Subject: [PATCH] Fix "time_to_second" helper Signed-off-by: Vitalii Chulak --- lib/auxiliary/time_helper.rb | 14 ++++++++--- spec/lib/auxiliary/time_helper_spec.rb | 32 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 spec/lib/auxiliary/time_helper_spec.rb diff --git a/lib/auxiliary/time_helper.rb b/lib/auxiliary/time_helper.rb index 61971c2b..1bcbaa20 100644 --- a/lib/auxiliary/time_helper.rb +++ b/lib/auxiliary/time_helper.rb @@ -4,9 +4,17 @@ module AutoHCK # Helper module module Helper - def time_to_seconds(time) - time.split(':').reverse.map.with_index { |a, i| a.to_i * (60**i) } - .reduce(:+) + def time_to_seconds(time_string) + match = time_string.match(/^(?:(\d+)\.)?(?:(\d+):)?(\d+)(?::(\d+(?:\.\d+)?))?$/) + + return 0 unless match + + days = match[1].to_i + hours = match[2].to_i + minutes = match[3].to_i + seconds = match[4].to_f + + (((((days * 24) + hours) * 60) + minutes) * 60) + seconds end def seconds_to_time(sec) diff --git a/spec/lib/auxiliary/time_helper_spec.rb b/spec/lib/auxiliary/time_helper_spec.rb new file mode 100644 index 00000000..6b84b12c --- /dev/null +++ b/spec/lib/auxiliary/time_helper_spec.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require_relative '../../../lib/auxiliary/time_helper' + +describe AutoHCK::Helper do + include AutoHCK::Helper + + describe '#time_to_seconds' do + # Define test cases with time strings and their expected second counts, + # with explicit calculations for clarity. + time_conversion_cases = { + # Format: hh:mm + '1:2' => (1 * 60 * 60) + (2 * 60), # 1 hour and 2 minutes in seconds + # Format: hh:mm:ss + '1:2:3' => (1 * 60 * 60) + (2 * 60) + 3, # 1 hour, 2 minutes, and 3 seconds + # Format: dd.hh:mm + '1.2:3' => (1 * 86_400) + (2 * 60 * 60) + (3 * 60), # 1 day, 2 hours, and 3 minutes + # Format: dd.hh:mm:ss + '1.2:3:4' => (1 * 86_400) + (2 * 60 * 60) + (3 * 60) + 4, # 1 day, 2 hours, 3 minutes, and 4 seconds + # Format: hh:mm:ss.ff + '1:2:3.22' => (1 * 60 * 60) + (2 * 60) + 3.22, # 1 hour, 2 minutes, and 3.22 seconds + # Format: dd.hh:mm:ss.ff + '1.2:3:4.22' => (1 * 86_400) + (2 * 60 * 60) + (3 * 60) + 4.22 # 1 day, 2 hours, 3 minutes, and 4.22 seconds + } + + time_conversion_cases.each do |time_string, seconds| + it "correctly converts '#{time_string}' to #{seconds} seconds" do + expect(time_to_seconds(time_string)).to eq(seconds) + end + end + end +end