Skip to content

Instantly share code, notes, and snippets.

@mclosson
Created June 12, 2017 18:39
Show Gist options
  • Save mclosson/8fbf1254252914ff0ae3da0662c3a35f to your computer and use it in GitHub Desktop.
Save mclosson/8fbf1254252914ff0ae3da0662c3a35f to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
class Strtime
def initialize(seconds)
@seconds = seconds
end
def to_s
raise ArgumentError if @seconds.to_i < 0
days = @seconds / 86400
hours = (@seconds % 86400) / 3600
minutes = (@seconds % 3600) / 60
seconds = @seconds % 60
days = if days > 1
"#{days} days"
elsif days == 1
"1 day"
else
nil
end
hours = if hours > 1
"#{hours} hours"
elsif hours == 1
"1 hour"
else
nil
end
minutes = if minutes > 1
"#{minutes} minutes"
elsif minutes == 1
"1 minute"
else
nil
end
seconds = if seconds > 1
"#{seconds} seconds"
elsif seconds == 1
"1 second"
else
nil
end
[days, hours, minutes, seconds].compact.join(" ")
end
end
class StrtimeTest < Minitest::Test
def test_minutes
assert_equal "", Strtime.new(0).to_s
assert_equal "1 second", Strtime.new(1).to_s
assert_equal "5 seconds", Strtime.new(5).to_s
assert_equal "1 minute", Strtime.new(60).to_s
assert_equal "1 minute 5 seconds", Strtime.new(65).to_s
assert_equal "2 minutes", Strtime.new(120).to_s
assert_equal "2 minutes 1 second", Strtime.new(121).to_s
assert_equal "2 minutes 2 seconds", Strtime.new(122).to_s
end
def test_hours
assert_equal "1 hour", Strtime.new(3600).to_s
assert_equal "1 hour 1 second", Strtime.new(3601).to_s
assert_equal "1 hour 2 seconds", Strtime.new(3602).to_s
assert_equal "1 hour 1 minute", Strtime.new(3660).to_s
assert_equal "1 hour 2 minutes", Strtime.new(3720).to_s
assert_equal "1 hour 1 minute 1 second", Strtime.new(3661).to_s
assert_equal "1 hour 2 minutes 1 second", Strtime.new(3721).to_s
# TODO: Add more test cases with mixed units
end
def test_days
assert_equal "1 day", Strtime.new(86400).to_s
assert_equal "2 days 2 hours 2 minutes 2 seconds", Strtime.new(180122).to_s
# TODO: Add more test cases with mixed units
end
def test_negative_number
assert_raises ArgumentError do
Strtime.new(-1).to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment