97 lines
1.7 KiB
Go
97 lines
1.7 KiB
Go
package stringset
|
|
|
|
import "maps"
|
|
|
|
type StringSet struct {
|
|
set map[string]bool
|
|
}
|
|
|
|
func NewStringSet() *StringSet {
|
|
return &StringSet{
|
|
set: make(map[string]bool, 0),
|
|
}
|
|
}
|
|
|
|
func NewStringSetWith(strings []string) *StringSet {
|
|
s := NewStringSet()
|
|
for _, str := range strings {
|
|
s.Add(str)
|
|
}
|
|
return s
|
|
}
|
|
|
|
func (s *StringSet) Add(str string) *StringSet {
|
|
s.set[str] = true
|
|
return s
|
|
}
|
|
|
|
func (s *StringSet) Remove(str string) *StringSet {
|
|
delete(s.set, str)
|
|
return s
|
|
}
|
|
|
|
func (s *StringSet) All() []string {
|
|
all := make([]string, 0)
|
|
for i := range s.set {
|
|
all = append(all, i)
|
|
}
|
|
return all
|
|
}
|
|
|
|
func (s *StringSet) Copy() *StringSet {
|
|
newSet := make(map[string]bool, 0)
|
|
maps.Copy(newSet, s.set)
|
|
return &StringSet{
|
|
set: newSet,
|
|
}
|
|
}
|
|
|
|
func (s *StringSet) Contains(str string) bool {
|
|
_, ok := s.set[str]
|
|
return ok
|
|
}
|
|
|
|
func (s *StringSet) Count() int {
|
|
return len(s.set)
|
|
}
|
|
|
|
func (s *StringSet) Equals(s2 *StringSet) bool {
|
|
if s.Count() != s2.Count() {
|
|
return false
|
|
}
|
|
for _, entry := range s2.All() {
|
|
_, ok := s.set[entry]
|
|
if !ok {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Diff returns a new StringSet that contains elements from s that were not present in s2
|
|
func (s *StringSet) Diff(s2 *StringSet) *StringSet {
|
|
temp := NewStringSet()
|
|
for _, item := range s.All() {
|
|
if !s2.Contains(item) {
|
|
temp.Add(item)
|
|
}
|
|
}
|
|
return temp
|
|
}
|
|
|
|
// Intersect returns a new StringSet that contains elements common to both s and s2
|
|
func (s *StringSet) Intersect(s2 *StringSet) *StringSet {
|
|
temp := NewStringSet()
|
|
for _, item := range s.All() {
|
|
if s2.Contains(item) {
|
|
temp.Add(item)
|
|
}
|
|
}
|
|
for _, item := range s2.All() {
|
|
if s.Contains(item) {
|
|
temp.Add(item)
|
|
}
|
|
}
|
|
return temp
|
|
}
|