aboutsummaryrefslogtreecommitdiffstats
path: root/util/set.lua
blob: 67f3dcaabfb37bd445bf99b85bb41b24cc2d095c (plain)
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
local ipairs, pairs = 
      ipairs, pairs;

module "set"

function new(list)
	local items = {};
	local set = { items = items };
	
	function set:add(item)
		items[item] = true;
	end
	
	function set:contains(item)
		return items[item];
	end
	
	function set:items()
		return items;
	end
	
	function set:remove(item)
		items[item] = nil;
	end
	
	function set:add_list(list)
		for _, item in ipairs(list) do
			items[item] = true;
		end
	end
	
	function set:include(otherset)
		for item in pairs(otherset) do
			items[item] = true;
		end
	end

	function set:exclude(otherset)
		for item in pairs(otherset) do
			items[item] = nil;
		end
	end
	
	if list then
		set:add_list(list);
	end
	
	return set;
end

function union(set1, set2)
	local set = new();
	local items = set.items;
	
	for item in pairs(set1.items) do
		items[item] = true;
	end

	for item in pairs(set2.items) do
		items[item] = true;
	end
	
	return set;
end

function difference(set1, set2)
	local set = new();
	local items = set.items;
	
	for item in pairs(set1.items) do
		items[item] = true;
	end

	for item in pairs(set2.items) do
		items[item] = nil;
	end
	
	return set;
end

return _M;