Template repo for tiny cross-platform apps that can be modified on phone, tablet or computer.
1local array = {}
2
3function array.find(arr, elem)
4 if type(elem) == 'function' then
5 for i,x in ipairs(arr) do
6 if elem(x) then
7 return x, i
8 end
9 end
10 else
11 for i,x in ipairs(arr) do
12 if x == elem then
13 return i
14 end
15 end
16 end
17 return nil
18end
19
20function array.any(arr, f)
21 for i,x in ipairs(arr) do
22 local result = f(x)
23 if result then
24 return result
25 end
26 end
27 return false
28end
29
30function array.all(arr, f)
31 for i,x in ipairs(arr) do
32 if not f(x) then
33 return false
34 end
35 end
36 return true
37end
38
39-- like ipairs, but support an index to start iterating from
40-- idx is inclusive; the first call to the iterator will return idx
41function array.each(arr, idx)
42 if idx then
43 if type(idx) ~= 'number' then
44 error("argument #2 to 'array.each' must be an integer if provided")
45 end
46 assert(idx >= 1, ("can't start iterating over an array from %d; the starting index needs to be at least 1"):format(idx))
47 end
48 idx = idx and idx-1 or 0
49 local iter = ipairs(arr)
50 return function()
51 local elem
52 idx, elem = iter(arr, idx)
53 return idx, elem
54 end
55end
56
57function array.join(a, b)
58 local result = {}
59 for _,v in ipairs(a) do table.insert(result, v) end
60 for _,v in ipairs(b) do table.insert(result, v) end
61 return result
62end
63
64function array.map(arr, f)
65 local result = {}
66 for _,v in ipairs(arr) do table.insert(result, f(v)) end
67 return result
68end
69
70function array.reduce(arr, init, f)
71 local result = init
72 for _,v in ipairs(arr) do
73 result = f(result, v)
74 end
75 return result
76end
77
78function array.sum(arr, f)
79 return array.reduce(array.map(arr, f), 0,
80 function(a, b) return a+b end)
81end
82
83function array.product(arr, f)
84 return array.reduce(array.map(arr, f), 1,
85 function(a, b) return a*b end)
86end
87
88function array.keep(arr, f)
89 local result = {}
90 for _,v in ipairs(arr) do
91 if f(v) then table.insert(result, v) end end
92 return result
93end
94
95function array.remove(arr, f)
96 local result = {}
97 for _,v in ipairs(arr) do
98 if not f(v) then table.insert(result, v) end end
99 return result
100end
101
102return array