package stringset
import (
"fmt"
"strings"
)
type Set map[string]struct{}
func New() Set {
return Set{}
}
func NewFromSlice(l []string) Set {
s := New()
for _, i := range l {
s[i] = struct{}{}
}
return s
}
func (s Set) String() string {
ret := strings.Builder{}
ret.WriteByte('{')
i := len(s)
for k := range s {
ret.WriteString(fmt.Sprintf("%q", k))
i--
if i != 0 {
ret.WriteString(", ")
}
}
ret.WriteByte('}')
return ret.String()
}
func (s Set) IsEmpty() bool {
if len(s) == 0 {
return true
}
return false
}
func (s Set) Has(elem string) bool {
_, ok := s[elem]
return ok
}
func (s Set) Add(elem string) {
s[elem] = struct{}{}
}
func Subset(s1, s2 Set) bool {
for k := range s1 {
_, ok := s2[k]
if !ok {
return false
}
}
return true
}
func Disjoint(s1, s2 Set) bool {
for k := range s1 {
_, ok := s2[k]
if ok {
return false
}
}
return true
}
func Equal(s1, s2 Set) bool {
for k := range s1 {
_, ok := s2[k]
if !ok {
return false
}
}
for k := range s2 {
_, ok := s1[k]
if !ok {
return false
}
}
return true
}
func Intersection(s1, s2 Set) Set {
ret := New()
for k := range s1 {
_, ok := s2[k]
if ok {
ret[k] = struct{}{}
}
}
return ret
}
func Difference(s1, s2 Set) Set {
ret := New()
for k := range s1 {
_, ok := s2[k]
if !ok {
ret[k] = struct{}{}
}
}
return ret
}
func Union(s1, s2 Set) Set {
ret := New()
for k := range s1 {
ret[k] = struct{}{}
}
for k := range s2 {
ret[k] = struct{}{}
}
return ret
}