From f956c247d32c4b9e74faaa5a5c76676e6f5dd9bd Mon Sep 17 00:00:00 2001 From: Vitalii Chulak Date: Tue, 13 Feb 2024 17:23:50 +0200 Subject: [PATCH] Rewrite time_to_seconds, add rspec Signed-off-by: Vitalii Chulak --- lib/auxiliary/time_helper.rb | 17 ++++++++++++----- spec/lib/auxiliary/test_helper_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) create mode 100644 spec/lib/auxiliary/test_helper_spec.rb diff --git a/lib/auxiliary/time_helper.rb b/lib/auxiliary/time_helper.rb index b463b316..321a3d38 100644 --- a/lib/auxiliary/time_helper.rb +++ b/lib/auxiliary/time_helper.rb @@ -4,11 +4,18 @@ module AutoHCK # Helper module module Helper - def time_to_seconds(time_str) - days, time_part = time_str.split('.') - hours, minutes, seconds = time_part.split(':').map(&:to_i) - total_hours = (days.to_i * 24) + hours - (total_hours * 3600) + (minutes * 60) + seconds + 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_i + fractional_seconds = "0.#{match[5]}".to_f + + ((days * 24 + hours) * 60 + minutes) * 60 + seconds + fractional_seconds end def seconds_to_time(sec) diff --git a/spec/lib/auxiliary/test_helper_spec.rb b/spec/lib/auxiliary/test_helper_spec.rb new file mode 100644 index 00000000..e324bf7f --- /dev/null +++ b/spec/lib/auxiliary/test_helper_spec.rb @@ -0,0 +1,23 @@ +require_relative '../../../lib/auxiliary/time_helper.rb' + +RSpec.describe AutoHCK::Helper do + include AutoHCK::Helper + + describe '#time_to_seconds' do + + time_strings = { + "1:2" => 3720, #hh:mm + "1:2:3" => 3723, #hh:mm:ss + "1.2:3" => 86400 + 7380, #dd.hh:mm + "1.2:3:4" => 86400 + 7380 + 4, #dd.hh:mm:ss + "1:2:3.22" => 3723.22, #hh:mm:ss.ff + "1.2:3:4.22" => 86400 + 7380 + 4.22, #dd.hh:mm:ss.ff + } + + time_strings.each do |time, expected| + it "correctly converts '#{time}' to #{expected} seconds" do + expect(time_to_seconds(time)).to eq(expected) + end + end + end +end \ No newline at end of file