~rootmos/lua-hack

79c9f4a5403b069287fb955643ad97de03fb4d8c — Gustav Behm 2 months ago 5247b67
Add a duration renderer
2 files changed, 53 insertions(+), 0 deletions(-)

A duration.lua
A duration.test.lua
A duration.lua => duration.lua +35 -0
@@ 0,0 1,35 @@
local M = {}

function M.parse(str)
    return 0
end

function M.render(sec)
    local str = ""

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

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

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

    if sec > 0 then
        str = str .. string.format("%ds", sec)
    end

    return str
end

return M

A duration.test.lua => duration.test.lua +18 -0
@@ 0,0 1,18 @@
local lu = require("luaunit")
local D = require("duration")

--function test_parse_1()
    --lu.assertEquals(D.parse("1s"), 1)
    --lu.assertEquals(D.parse("1m"), 60)
    --lu.assertEquals(D.parse("1h"), 60*60)
    --lu.assertEquals(D.parse("1d"), 24*60*60)
--end

function test_render_1()
    lu.assertEquals("1s", D.render(1))
    lu.assertEquals("1m", D.render(60))
    lu.assertEquals("1h", D.render(60*60))
    lu.assertEquals("1d", D.render(24*60*60))
end

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