Skip to content

Commit

Permalink
Fix "time_to_second" helper
Browse files Browse the repository at this point in the history
Signed-off-by: Vitalii Chulak <[email protected]>
  • Loading branch information
Jedoku authored and kostyanf14 committed Feb 14, 2024
1 parent e2b0a2b commit 69f3431
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/auxiliary/time_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
32 changes: 32 additions & 0 deletions spec/lib/auxiliary/time_helper_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 69f3431

Please sign in to comment.