github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/set/any.go (about) 1 package set 2 3 type AnyHashSet map[interface{}]struct{} 4 5 func NewAnyHashSet(items ...interface{}) AnyHashSet { 6 set := AnyHashSet{} 7 for _, item := range items { 8 set[item] = struct{}{} 9 } 10 return set 11 } 12 13 func (s AnyHashSet) Add(items ...interface{}) { 14 for _, item := range items { 15 s[item] = struct{}{} 16 } 17 } 18 19 func (s AnyHashSet) Remove(items ...interface{}) { 20 for _, item := range items { 21 delete(s, item) 22 } 23 } 24 25 func (s AnyHashSet) Values() []interface{} { 26 values := make([]interface{}, 0, len(s)) 27 for k := range s { 28 values = append(values, k) 29 } 30 return values 31 } 32 33 func (s AnyHashSet) Range(fn func(item interface{})) { 34 for k := range s { 35 fn(k) 36 } 37 } 38 39 func (s AnyHashSet) Contains(item string) bool { 40 _, ok := s[item] 41 return ok 42 } 43 44 func (s AnyHashSet) ContainAll(items ...interface{}) bool { 45 for _, item := range items { 46 if _, ok := s[item]; !ok { 47 return false 48 } 49 } 50 return true 51 } 52 53 func (s AnyHashSet) ContainAny(items ...string) bool { 54 for _, item := range items { 55 if _, ok := s[item]; ok { 56 return true 57 } 58 } 59 return false 60 } 61 62 func (s AnyHashSet) Size() int { 63 return len(s) 64 } 65 66 func (s AnyHashSet) Union(o AnyHashSet) AnyHashSet { 67 n := NewAnyHashSet(s.Values()...) 68 for k := range o { 69 n[k] = struct{}{} 70 } 71 return n 72 } 73 74 func (s AnyHashSet) InterSection(o AnyHashSet) AnyHashSet { 75 n := NewAnyHashSet() 76 for k := range s { 77 if _, ok := o[k]; ok { 78 n[k] = struct{}{} 79 } 80 } 81 return n 82 } 83 84 func (s AnyHashSet) Difference(o AnyHashSet) AnyHashSet { 85 n := NewAnyHashSet(s.Values()...) 86 n.Remove(o.Values()...) 87 return n 88 } 89 90 func (s AnyHashSet) IsSuperSet(o AnyHashSet) bool { 91 return s.ContainAll(o.Values()...) 92 } 93 94 func (s AnyHashSet) IsSubSet(o AnyHashSet) bool { 95 return o.ContainAll(s.Values()...) 96 }