~rootmos/lua-hack

9a1c4e0a9af07693d29709fbf3fabcd5871b18da — Gustav Behm 2 months ago bc2163e duration
Render milliseconds
2 files changed, 27 insertions(+), 11 deletions(-)

M duration.lua
M duration.test.lua
M duration.lua => duration.lua +19 -11
@@ 28,26 28,34 @@ end
function M.render(sec)
    local str = ""

    if sec >= 86400 then
        local d = sec // 86400
    local s, f = math.modf(sec)

    if s >= 86400 then
        local d = s // 86400
        str = str .. string.format("%dd", d)
        sec = sec - d * 86400
        s = s - d * 86400
    end

    if sec >= 3600 then
        local h = sec // 3600
    if s >= 3600 then
        local h = s // 3600
        str = str .. string.format("%dh", h)
        sec = sec - h * 3600
        s = s - h * 3600
    end

    if sec >= 60 then
        local m = sec // 60
    if s >= 60 then
        local m = s // 60
        str = str .. string.format("%dm", m)
        sec = sec - m * 60
        s = s - m * 60
    end

    if sec > 0 then
        str = str .. string.format("%ds", sec)
    local ms = math.floor(f*1e3+0.5)

    if s > 0 or ms > 0 then
        if ms == 0 then
            str = str .. string.format("%ds", s)
        else
            str = str .. string.format("%.3fs", s + 0.001*ms)
        end
    end

    return str

M duration.test.lua => duration.test.lua +8 -0
@@ 53,4 53,12 @@ function test_render_parse_roundtrip()
    end
end

function test_render_ms()
    lu.assertEquals(D.render(7.1), "7.100s")
    lu.assertEquals(D.render(7.01), "7.010s")
    lu.assertEquals(D.render(7.0012), "7.001s")
    lu.assertEquals(D.render(7.0009), "7.001s")
    lu.assertEquals(D.render(7.0001), "7s")
end

os.exit(lu.LuaUnit.run())