mirror of
https://gitea.invidious.io/iv-org/shard-spectator.git
synced 2024-08-15 00:53:35 +00:00
Move human time to its own type to share it
This commit is contained in:
parent
aabc25ad4f
commit
72aa72781a
2 changed files with 42 additions and 26 deletions
41
src/spectator/formatting/human_time.cr
Normal file
41
src/spectator/formatting/human_time.cr
Normal file
|
@ -0,0 +1,41 @@
|
|||
module Spectator::Formatting
|
||||
# Provides a more human-friendly formatting for a time span.
|
||||
# This produces a string with the minimum of
|
||||
# microseconds, milliseconds, seconds, minutes, hours, or days.
|
||||
private struct HumanTime
|
||||
@string : String
|
||||
|
||||
# Creates the wrapper
|
||||
def initialize(span)
|
||||
@string = simplify(span)
|
||||
end
|
||||
|
||||
# Produces the human-friendly string for a time span.
|
||||
def to_s(io)
|
||||
io << @string
|
||||
end
|
||||
|
||||
# Does the actual work of converting a time span to string.
|
||||
private def simplify(span)
|
||||
millis = span.total_milliseconds
|
||||
return "#{(millis * 1000).round.to_i} microseconds" if millis < 1
|
||||
|
||||
seconds = span.total_seconds
|
||||
return "#{millis.round(2)} milliseconds" if seconds < 1
|
||||
return "#{seconds.round(2)} seconds" if seconds < 60
|
||||
|
||||
int_seconds = seconds.to_i
|
||||
minutes = int_seconds / 60
|
||||
int_seconds %= 60
|
||||
return sprintf("%i:%02i", minutes, int_seconds) if minutes < 60
|
||||
|
||||
hours = minutes / 60
|
||||
minutes %= 60
|
||||
return sprintf("%i:%02i:%02i", hours, minutes, int_seconds) if hours < 24
|
||||
|
||||
days = hours / 24
|
||||
hours %= 24
|
||||
return sprintf("%i days %i:%02i:%02i", days, hours, minutes, int_seconds)
|
||||
end
|
||||
end
|
||||
end
|
|
@ -18,32 +18,7 @@ module Spectator::Formatting
|
|||
# ```
|
||||
def to_s(io)
|
||||
io << "Finished in "
|
||||
io << human_time(@runtime)
|
||||
end
|
||||
|
||||
# Provides a more human-friendly formatting for a time span.
|
||||
# This produces a string with the minimum of
|
||||
# microseconds, milliseconds, seconds, minutes, hours, or days.
|
||||
private def human_time(span)
|
||||
millis = span.total_milliseconds
|
||||
return "#{(millis * 1000).round.to_i} microseconds" if millis < 1
|
||||
|
||||
seconds = span.total_seconds
|
||||
return "#{millis.round(2)} milliseconds" if seconds < 1
|
||||
return "#{seconds.round(2)} seconds" if seconds < 60
|
||||
|
||||
int_seconds = seconds.to_i
|
||||
minutes = int_seconds / 60
|
||||
int_seconds %= 60
|
||||
return sprintf("%i:%02i", minutes, int_seconds) if minutes < 60
|
||||
|
||||
hours = minutes / 60
|
||||
minutes %= 60
|
||||
return sprintf("%i:%02i:%02i", hours, minutes, int_seconds) if hours < 24
|
||||
|
||||
days = hours / 24
|
||||
hours %= 24
|
||||
return sprintf("%i days %i:%02i:%02i", days, hours, minutes, int_seconds)
|
||||
io << HumanTime.new(@runtime)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue