github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/set/string_hash_set.go (about)

     1  package set
     2  
     3  type StringHashSet map[string]struct{}
     4  
     5  func NewStringHashSet(items ...string) StringHashSet {
     6  	set := StringHashSet{}
     7  	for _, item := range items {
     8  		set[item] = struct{}{}
     9  	}
    10  	return set
    11  }
    12  
    13  func (s StringHashSet) Add(items ...string) {
    14  	for _, item := range items {
    15  		s[item] = struct{}{}
    16  	}
    17  }
    18  
    19  func (s StringHashSet) Remove(items ...string) {
    20  	for _, item := range items {
    21  		delete(s, item)
    22  	}
    23  }
    24  
    25  func (s StringHashSet) Values() []string {
    26  	values := make([]string, 0, len(s))
    27  	for k := range s {
    28  		values = append(values, k)
    29  	}
    30  	return values
    31  }
    32  
    33  func (s StringHashSet) Range(fn func(item string)) {
    34  	for k := range s {
    35  		fn(k)
    36  	}
    37  }
    38  
    39  func (s StringHashSet) Contains(item string) bool {
    40  	_, ok := s[item]
    41  	return ok
    42  }
    43  
    44  func (s StringHashSet) ContainAll(items ...string) 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 StringHashSet) 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 StringHashSet) Size() int {
    63  	return len(s)
    64  }
    65  
    66  func (s StringHashSet) Union(o StringHashSet) StringHashSet {
    67  	n := NewStringHashSet(s.Values()...)
    68  	for k := range o {
    69  		n[k] = struct{}{}
    70  	}
    71  	return n
    72  }
    73  
    74  func (s StringHashSet) InterSection(o StringHashSet) StringHashSet {
    75  	n := NewStringHashSet()
    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 StringHashSet) Difference(o StringHashSet) StringHashSet {
    85  	n := NewStringHashSet(s.Values()...)
    86  	n.Remove(o.Values()...)
    87  	return n
    88  }
    89  
    90  func (s StringHashSet) IsSuperSet(o StringHashSet) bool {
    91  	return s.ContainAll(o.Values()...)
    92  }
    93  
    94  func (s StringHashSet) IsSubSet(o StringHashSet) bool {
    95  	return o.ContainAll(s.Values()...)
    96  }