summaryrefslogtreecommitdiffstats
path: root/scripts/lib/common.lua
blob: 055e7833d5cf1413752d4c72b8a113065e88d5d3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
local utils = require 'pandoc.utils'

function string.split(str, sep)
    sep = sep or '%s'

    local parts = pandoc.List()

    for field, s in str:gmatch("([^" .. sep .. "]*)(" .. sep .. "?)") do
        parts:insert(field)
        if s == "" then return parts end
    end
end

function pandoc.List:flatten()
    local result = pandoc.List()

    for i = 1, #self do result:extend(self[i]) end

    return result
end

function pandoc.List:flatMap(fn)
    return self:map(fn):flatten()
end

function pandoc.List:filterMap(fn)
    local mapped = self:map(fn)
    local result = pandoc.List()

    for i = 1, #mapped do
        local val = mapped[i]
        if val then
            result:insert(val)
        end
    end

    return result
end

function pandoc.List:take(n)
    if n >= #self then return self end

    local result = pandoc.List()

    for i = 1, n do result:insert(self[i]) end

    return result
end

function pandoc.List:skip(n)
    local result = pandoc.List()

    if n >= #self then return result end

    for i = n + 1, #self do result:insert(self[i]) end

    return result
end

function pandoc.List:shuffle()
    for i = #self, 2, -1 do
        local j = math.random(i)
        self[i], self[j] = self[j], self[i]
    end

    return self
end

function dump(o)
    if type(o) == 'table' then
        local s = '{ '
        for k, v in pairs(o) do
            if type(k) ~= 'number' then k = '"' .. k .. '"' end
            s = s .. '[' .. k .. '] = ' .. dump(v) .. ','
        end
        return s .. '} '
    else
        return tostring(o)
    end
end

function prep_layout(layout)
    layout = utils.stringify(layout)
    return { id = layout, ["is_" .. layout] = true }
end

return {
    dump = dump,
    prep_layout = prep_layout
}