~rootmos/lua-hack

70c14f02924f99ae342860a7cb0b9952993b7ce8 — Gustav Behm 2 months ago 79c9f4a
Implement a duration parser
2 files changed, 54 insertions(+), 7 deletions(-)

M duration.lua
M duration.test.lua
M duration.lua => duration.lua +22 -1
@@ 1,7 1,28 @@
local M = {}

function M.parse(str)
    return 0
    if str == "" then
        return 0
    end

    local sec = nil
    for q, u in string.gmatch(str, "(%d+)([dhms])") do
        if sec == nil then
            sec = 0
        end

        if u == "d" then
            sec = sec + tonumber(q) * 86400
        elseif u == "h" then
            sec = sec + tonumber(q) * 3600
        elseif u == "m" then
            sec = sec + tonumber(q) * 60
        elseif u == "s" then
            sec = sec + tonumber(q)
        end
    end

    return sec
end

function M.render(sec)

M duration.test.lua => duration.test.lua +32 -6
@@ 1,12 1,19 @@
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_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_parse_2()
    lu.assertEquals(D.parse("1s2s"), 3)
    lu.assertEquals(D.parse("1m2s"), 60+2)
    lu.assertEquals(D.parse("1h2s"), 60*60+2)
    lu.assertEquals(D.parse("1d2m"), 24*60*60+2*60)
end

function test_render_1()
    lu.assertEquals("1s", D.render(1))


@@ 15,4 22,23 @@ function test_render_1()
    lu.assertEquals("1d", D.render(24*60*60))
end

function test_render_2()
    lu.assertEquals("3s", D.render(3))
    lu.assertEquals("1m2s", D.render(60+2))
    lu.assertEquals("1h2s", D.render(60*60+2))
    lu.assertEquals("1d2m", D.render(24*60*60+2*60))
end

function test_parse_0()
    lu.assertEquals(D.parse(""), 0)
    lu.assertEquals(D.parse("0s"), 0)
    lu.assertEquals(D.parse("0m"), 0)
    lu.assertEquals(D.parse("0h"), 0)
    lu.assertEquals(D.parse("0d"), 0)
end

function test_render_0()
    lu.assertEquals(D.render(0), "")
end

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