/
Set.lua
149 lines (132 loc) · 2.39 KB
/
Set.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
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
138
139
140
141
142
143
144
145
146
147
148
149
--[=[
Utility functions involving sets, which are tables with the key as an index, and the value as a
truthy value.
@class Set
]=]
local Set = {}
--[=[
Unions the set with the other set, making a copy.
@param set table
@param otherSet table
@return table
]=]
function Set.union(set, otherSet)
local newSet = {}
for key, _ in pairs(set) do
newSet[key] = true
end
for key, _ in pairs(otherSet) do
newSet[key] = true
end
return newSet
end
--[=[
Unions the set with the other set, updating the `set`
@param set table
@param otherSet table
@return table
]=]
function Set.unionUpdate(set, otherSet)
for key, _ in pairs(otherSet) do
set[key] = true
end
end
--[=[
Finds the set intersection betwen the two sets
@param set table
@param otherSet table
@return table
]=]
function Set.intersection(set, otherSet)
local newSet = {}
for key, _ in pairs(set) do
if otherSet[key] ~= nil then
newSet[key] = true
end
end
return newSet
end
--[=[
Makes a copy of the set, making the values as true.
@param set table
@return table
]=]
function Set.copy(set)
local newSet = {}
for key, _ in pairs(set) do
newSet[key] = true
end
return newSet
end
--[=[
Makes a new set from the given keys of a table
@param tab table
@return table
]=]
function Set.fromKeys(tab)
local newSet = {}
for key, _ in pairs(tab) do
newSet[key] = true
end
return newSet
end
--[=[
Converts a set from table values.
@param tab table
@return table
]=]
function Set.fromTableValue(tab)
local set = {}
for _, value in pairs(tab) do
set[value] = true
end
return set
end
--[=[
Converts a set from a list
@function fromList
@param tab table
@return table
@within Set
]=]
Set.fromList = Set.fromTableValue
--[=[
Converts a set to a list
@param set table
@return table
]=]
function Set.toList(set)
local list = {}
for value, _ in pairs(set) do
table.insert(list, value)
end
return list
end
--[=[
Converts a set to a list
@param set table
@param otherSet table
@return table
]=]
function Set.differenceUpdate(set, otherSet)
for value, _ in pairs(otherSet) do
set[value] = nil
end
end
--[=[
Computes the set difference between the two sets
@param set table
@param otherSet table
@return table
]=]
function Set.difference(set, otherSet)
local newSet = {}
for key, _ in pairs(set) do
newSet[key] = true
end
for key, _ in pairs(otherSet) do
newSet[key] = nil
end
return newSet
end
return Set