github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/container/set/hashset.go (about) 1 package set 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 var itemExists = struct{}{} 9 10 type HashSet struct { 11 Items map[interface{}]struct{} 12 } 13 14 func NewSet(values ...interface{}) *HashSet { 15 set := &HashSet{Items: make(map[interface{}]struct{})} 16 if len(values) > 0 { 17 set.Add(values...) 18 } 19 return set 20 } 21 22 func (set *HashSet) Add(items ...interface{}) { 23 for _, item := range items { 24 set.Items[item] = itemExists 25 } 26 } 27 28 func (set *HashSet) Remove(items ...interface{}) { 29 for _, item := range items { 30 delete(set.Items, item) 31 } 32 } 33 34 func (set *HashSet) Contains(items ...interface{}) bool { 35 for _, item := range items { 36 if _, contains := set.Items[item]; !contains { 37 return false 38 } 39 } 40 return true 41 } 42 43 func (set *HashSet) Empty() bool { 44 return set.Size() == 0 45 } 46 47 func (set *HashSet) Size() int { 48 return len(set.Items) 49 } 50 51 func (set *HashSet) Clear() { 52 set.Items = make(map[interface{}]struct{}) 53 } 54 55 func (set *HashSet) Values() []interface{} { 56 values := make([]interface{}, set.Size()) 57 count := 0 58 for item := range set.Items { 59 values[count] = item 60 count++ 61 } 62 return values 63 } 64 65 func (set *HashSet) String() string { 66 str := "HashSet\n" 67 var items []string 68 for k := range set.Items { 69 items = append(items, fmt.Sprintf("%v", k)) 70 } 71 str += strings.Join(items, ", ") 72 return str 73 }