diff --git a/README.md b/README.md index 4a4b9b8..34ddda8 100644 --- a/README.md +++ b/README.md @@ -24,16 +24,14 @@ type myMap = Map[string,int] // the equal sign here is critical! type myStdMap = StdMap[string, int] func main() { - m := new(Map[string, int]) - - m.Copy(myStdMap{"b":2, "c":3}) - m.Set("a",1) - - sum := 0 - for v := range m.All() { - sum += v - } - fmt.Print(sum) + m := new(Map[string, int]) + m.Copy(myStdMap{"b":2, "c":3}) + m.Set("a",1) + sum := 0 + for v := range m.All() { + sum += v + } + fmt.Print(sum) } ``` diff --git a/set.go b/set.go index a4b2a83..c806899 100644 --- a/set.go +++ b/set.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "iter" - "slices" ) // Set is a collection that keeps track of membership. @@ -168,9 +167,8 @@ func (m *Set[K]) UnmarshalJSON(in []byte) (err error) { // String returns the set as a string. func (m *Set[K]) String() string { - vals := slices.Clone(m.Values()) ret := "{" - for i, v := range vals { + for i, v := range m.Values() { ret += fmt.Sprintf("%#v", v) if i < m.Len()-1 { ret += "," diff --git a/set_ordered.go b/set_ordered.go index 5ce05af..f91c5ec 100644 --- a/set_ordered.go +++ b/set_ordered.go @@ -58,3 +58,18 @@ func (m *OrderedSet[K]) All() iter.Seq[K] { v := m.Values() return slices.Values(v) } + +// Clone returns a copy of the Set. This is a shallow clone: +// the new keys and values are set using ordinary assignment. +func (m *OrderedSet[K]) Clone() *OrderedSet[K] { + m1 := NewOrderedSet[K]() + m1.items = m.items.Clone() + return m1 +} + +// Add adds the value to the set. +// If the value already exists, nothing changes. +func (m *OrderedSet[K]) Add(k ...K) SetI[K] { + m.Set.Add(k...) + return m +} diff --git a/set_ordered_test.go b/set_ordered_test.go index 2e69d0b..d45fde9 100644 --- a/set_ordered_test.go +++ b/set_ordered_test.go @@ -101,3 +101,12 @@ func TestOrderedSet_Range(t *testing.T) { }) } } + +func TestOrderedSet_Clone(t *testing.T) { + m1 := NewOrderedSet("a", "b", "c") + m2 := m1.Clone() + assert.True(t, m1.Equal(m2)) + + m2.Add("d") + assert.False(t, m1.Equal(m2)) +} diff --git a/seti.go b/seti.go index f5db475..b3f834c 100644 --- a/seti.go +++ b/seti.go @@ -15,6 +15,5 @@ type SetI[K comparable] interface { Delete(k K) All() iter.Seq[K] Insert(seq iter.Seq[K]) - Clone() *Set[K] DeleteFunc(del func(K) bool) }