Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "time_to_second" helper #300

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Jedoku marked this conversation as resolved.
Show resolved Hide resolved
# 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)
Fixed Show fixed Hide fixed
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
Loading