-
Notifications
You must be signed in to change notification settings - Fork 1
/
array.lua
78 lines (69 loc) · 1.28 KB
/
array.lua
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
local array = {};
function Array(t)
return setmetatable(t, {__index = array})
end
Array_from_values = function (table)
local new_array = {}
local j = 1
for k,v in pairs(table) do
new_array[j] = v
j = j + 1
end
return Array(new_array)
end
function array.map(a, func)
local new_array = {}
for i,v in ipairs(a) do
new_array[i] = func(v)
end
return Array(new_array)
end
function array.for_each(a, func)
for _,v in ipairs(a) do
local ret = func(v)
if ret then
break
end
end
end
function array.filter(a, func)
local new_array = {}
local j = 1
for _,v in ipairs(a) do
if (func(v)) then
new_array[j] = v
j = j + 1
end
end
return Array(new_array)
end
function array.size(a)
return #a
end
function array.find(a, func)
local f = a:filter(func)
if (f:size() > 0) then
return f[1]
end
return nil
end
function array.contains(a, el)
return a:filter(function (e)
return e == el
end):size() > 0
end
function array.to_string(a)
local str = "[ "
a:for_each(function(v)
if type(v) == "array" then
str = str .. v:tostring()
elseif type(v) == "table" then
str = str .. Array(v):tostring()
else
str = str .. v
end
str = str .. ", "
end)
str = str .. " ]"
return str
end