1
// Copyright (c) 2016-2019 Uber Technologies, Inc.
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
7
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
18
// Set is a nifty little wrapper for common set operations on a map. Because it
19
// is equivalent to a map, make/range/len will still work with Set.
20
type Set map[string]struct{}
22
// FromSlice converts a slice of strings into a Set.
23
func FromSlice(xs []string) Set {
25
for _, x := range xs {
31
// New creates a new Set with xs.
32
func New(xs ...string) Set {
37
func (s Set) Add(x string) {
41
// Remove removes x from s.
42
func (s Set) Remove(x string) {
46
// Has returns true if x is in s.
47
func (s Set) Has(x string) bool {
52
// Sub returns a new set which is the result of s minus s2.
53
func (s Set) Sub(s2 Set) Set {
63
// ToSlice converts s to a slice.
64
func (s Set) ToSlice() []string {
72
// Equal returns whether s1 and s2 contain the same elements.
73
func Equal(s1 Set, s2 Set) bool {
74
if len(s1) != len(s2) {
85
// Copy returns a copy of s.
86
func (s Set) Copy() Set {
87
c := make(Set, len(s))
94
// Random returns a random element in s. Returns error if s is empty.
95
func (s Set) Random() (string, error) {
99
return "", errors.New("set is empty")
102
// Sample samples n random elements from s. If there are <= n elements in s,
103
// returns the whole set.
104
func (s Set) Sample(n int) Set {