-
Notifications
You must be signed in to change notification settings - Fork 1
/
set.go
116 lines (100 loc) · 2.32 KB
/
set.go
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
// Copyright 2022 Tomas Machalek <tomas.machalek@gmail.com>
// Copyright 2022 Institute of the Czech National Corpus,
// Faculty of Arts, Charles University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package collections
import (
"sort"
"golang.org/x/exp/constraints"
)
type Set[T constraints.Ordered] struct {
data map[T]bool
}
func (set *Set[T]) testAndInit() {
if set.data == nil {
set.data = make(map[T]bool)
}
}
func (set *Set[T]) Add(value T) {
set.testAndInit()
set.data[value] = true
}
func (set *Set[T]) Remove(value T) {
set.testAndInit()
delete(set.data, value)
}
func (set *Set[T]) Contains(value T) bool {
set.testAndInit()
_, ok := set.data[value]
return ok
}
func (set *Set[T]) ToSlice() []T {
set.testAndInit()
ans := make([]T, 0, len(set.data))
for k := range set.data {
ans = append(ans, k)
}
return ans
}
func (set *Set[T]) ToOrderedSlice() []T {
ans := set.ToSlice()
sort.Slice(
ans,
func(i, j int) bool {
return ans[i] < ans[j]
},
)
return ans
}
func (set *Set[T]) ForEach(fn func(item T)) {
for k := range set.data {
fn(k)
}
}
func (set *Set[T]) Union(other Set[T]) *Set[T] {
set.testAndInit()
ans := NewSet(set.ToSlice()...)
other.ForEach(func(item T) {
ans.Add(item)
})
return ans
}
func (set *Set[T]) Size() int {
return len(set.data)
}
func (set *Set[T]) Sub(other *Set[T]) *Set[T] {
set.testAndInit()
ans := NewSet(set.ToSlice()...)
other.ForEach(func(item T) {
ans.Remove(item)
})
return ans
}
func (set *Set[T]) Intersect(other *Set[T]) *Set[T] {
set.testAndInit()
ans := NewSet([]T{}...)
other.ForEach(func(item T) {
if set.Contains(item) {
ans.Add(item)
}
})
return ans
}
func NewSet[T constraints.Ordered](values ...T) *Set[T] {
ans := Set[T]{data: make(map[T]bool)}
for _, v := range values {
ans.data[v] = true
}
return &ans
}