add copying function

This commit is contained in:
dave 2024-06-01 16:45:18 -07:00
parent 12572223be
commit a12a1c4c59
2 changed files with 21 additions and 1 deletions

10
set.go
View File

@ -1,5 +1,7 @@
package stringset
import "maps"
type StringSet struct {
set map[string]bool
}
@ -36,6 +38,14 @@ func (s *StringSet) All() []string {
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

View File

@ -79,10 +79,20 @@ func TestNewStringSetWith(t *testing.T) {
}
s.Add("foo").Add("qux")
// s = noo, lol
// s = noo, lol, foo, qux
if !s.Equals(NewStringSetWith([]string{"noo", "lol", "foo", "qux"})) {
t.Errorf("unexpected result from Add() chaining")
}
s2 = s.Copy().Remove("noo")
// s = lol, foo, qux
if !s2.Equals(NewStringSetWith([]string{"lol", "foo", "qux"})) {
t.Errorf("unexpected result after cloning and removing")
}
if !s.Equals(NewStringSetWith([]string{"noo", "lol", "foo", "qux"})) {
t.Errorf("unexpected result original was modified via the clone")
}
}
func stringSlicesMatch(s1, s2 []string) bool {