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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
local astal = require("astal")
local Variable = require("astal").Variable
local Astal = require("astal.gtk3").Astal
local GLib = astal.require("GLib")
local lib
lib = {
--- get path to file in astal source
src = function(path)
local str = debug.getinfo(2, "S").source:sub(2)
local src = str:match("(.*/)") or str:match("(.*\\)") or "./"
return src .. path
end,
--- map an array with a function
map = function(array, func)
local new_arr = {}
for i, v in ipairs(array) do
new_arr[i] = func(v, i)
end
return new_arr
end,
--- filter an array with a function
filter = function(array, func)
local new_arr = {}
for i, v in ipairs(array) do
if func(v, i) then
new_arr[i] = v
end
end
return new_arr
end,
--- sort an array of object on a key
sort = function(array, func)
-- default func to sort on attr 'id'
if not func then
func = 'id'
end
-- make function if just provided with attribute
if type(func) ~= 'function' then
local key = func
func = function(a, b) return a[key] < b[key] end
end
-- copy to new array
local new_arr = {}
for i, v in ipairs(array) do
new_arr[i] = v
end
-- sort and return
table.sort(new_arr, func)
return new_arr
end,
--- returns if value is an array
is_array = function(val)
return type(val) == 'table'
end,
--- returns if value is an string
is_string = function(val)
return type(val) == 'string'
end,
--- returns if value is nil
is_nil = function(val)
return val == nil
end,
--- returns length of table or string
count = function(val)
if lib.is_array(val) then
return #val
elseif lib.is_string(val) then
return val:len()
elseif lib.is_nil(val) then
return 0
else
return nil
end
end,
--- returns if a table is empty
empty = function(array)
return lib.count(array) == 0
end,
--- negates value
neg = function(val)
return not val
end,
--- better truthy function
is_true = function(val)
-- zero is false
if val == 0 then
return false
end
-- empty array or string is false
if lib.empty(val) then
return false
end
-- default truthyness
return val and true or false
end,
--- better fasly function
is_false = function(val)
return not lib.is_true(val)
end,
--- checks if a file exists
file_exists = function(path)
return GLib.file_test(path, "EXISTS")
end,
--- checks if a string is an icon
is_icon = function(icon)
return Astal.Icon.lookup_icon(icon) ~= nil
end,
--- formats a time
time = function(time, format)
format = format or "%H:%M"
return GLib.DateTime.new_from_unix_local(time):format(format)
end,
}
return lib
|