Add time module with to_duration_string
Which turn a float into a `mm:ss` string
This commit is contained in:
23
src/musicplayer/time/time.gleam
Normal file
23
src/musicplayer/time/time.gleam
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import gleam/float
|
||||||
|
import gleam/int
|
||||||
|
import gleam/string
|
||||||
|
|
||||||
|
pub fn to_duration_string(seconds: Float) -> String {
|
||||||
|
let total =
|
||||||
|
seconds
|
||||||
|
|> float.max(0.0)
|
||||||
|
|> float.truncate
|
||||||
|
|
||||||
|
let minutes = total / 60
|
||||||
|
let seconds = total % 60
|
||||||
|
|
||||||
|
let mins =
|
||||||
|
int.to_string(minutes)
|
||||||
|
|> string.pad_start(to: 2, with: "0")
|
||||||
|
|
||||||
|
let secs =
|
||||||
|
int.to_string(seconds)
|
||||||
|
|> string.pad_start(to: 2, with: "0")
|
||||||
|
|
||||||
|
mins <> ":" <> secs
|
||||||
|
}
|
||||||
32
test/musicplayer/time/time_test.gleam
Normal file
32
test/musicplayer/time/time_test.gleam
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import gleam/list
|
||||||
|
import gleeunit
|
||||||
|
|
||||||
|
import musicplayer/time/time
|
||||||
|
|
||||||
|
pub fn main() -> Nil {
|
||||||
|
gleeunit.main()
|
||||||
|
}
|
||||||
|
|
||||||
|
type TestCase {
|
||||||
|
TestCase(seconds: Float, expected: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_duration_string_test() {
|
||||||
|
let test_cases = [
|
||||||
|
TestCase(-1.0, "00:00"),
|
||||||
|
TestCase(0.0, "00:00"),
|
||||||
|
TestCase(9.0, "00:09"),
|
||||||
|
TestCase(10.0, "00:10"),
|
||||||
|
TestCase(11.0, "00:11"),
|
||||||
|
TestCase(60.0, "01:00"),
|
||||||
|
TestCase(61.0, "01:01"),
|
||||||
|
TestCase(120.0, "02:00"),
|
||||||
|
TestCase(600.0, "10:00"),
|
||||||
|
TestCase(6000.0, "100:00"),
|
||||||
|
TestCase(6001.0, "100:01"),
|
||||||
|
]
|
||||||
|
|
||||||
|
list.each(test_cases, fn(tc) {
|
||||||
|
assert tc.expected == time.to_duration_string(tc.seconds)
|
||||||
|
})
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user