-
Notifications
You must be signed in to change notification settings - Fork 407
/
stringset.go
114 lines (101 loc) · 2.36 KB
/
stringset.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
// Copyright (c) 2016-2019 Uber Technologies, Inc.
//
// 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 stringset
import "errors"
// Set is a nifty little wrapper for common set operations on a map. Because it
// is equivalent to a map, make/range/len will still work with Set.
type Set map[string]struct{}
// FromSlice converts a slice of strings into a Set.
func FromSlice(xs []string) Set {
s := make(Set)
for _, x := range xs {
s.Add(x)
}
return s
}
// New creates a new Set with xs.
func New(xs ...string) Set {
return FromSlice(xs)
}
// Add adds x to s.
func (s Set) Add(x string) {
s[x] = struct{}{}
}
// Remove removes x from s.
func (s Set) Remove(x string) {
delete(s, x)
}
// Has returns true if x is in s.
func (s Set) Has(x string) bool {
_, ok := s[x]
return ok
}
// Sub returns a new set which is the result of s minus s2.
func (s Set) Sub(s2 Set) Set {
result := make(Set)
for x := range s {
if !s2.Has(x) {
result.Add(x)
}
}
return result
}
// ToSlice converts s to a slice.
func (s Set) ToSlice() []string {
var xs []string
for x := range s {
xs = append(xs, x)
}
return xs
}
// Equal returns whether s1 and s2 contain the same elements.
func Equal(s1 Set, s2 Set) bool {
if len(s1) != len(s2) {
return false
}
for x := range s1 {
if !s2.Has(x) {
return false
}
}
return true
}
// Copy returns a copy of s.
func (s Set) Copy() Set {
c := make(Set, len(s))
for x := range s {
c.Add(x)
}
return c
}
// Random returns a random element in s. Returns error if s is empty.
func (s Set) Random() (string, error) {
for x := range s {
return x, nil
}
return "", errors.New("set is empty")
}
// Sample samples n random elements from s. If there are <= n elements in s,
// returns the whole set.
func (s Set) Sample(n int) Set {
c := make(Set, n)
for x := range s {
if n == 0 {
break
}
c.Add(x)
n--
}
return s
}