From a12a1c4c5996343cd04c4dccd5b47874a57f33bb Mon Sep 17 00:00:00 2001 From: dave Date: Sat, 1 Jun 2024 16:45:18 -0700 Subject: [PATCH] add copying function --- set.go | 10 ++++++++++ set_test.go | 12 +++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/set.go b/set.go index ac1294c..5005021 100644 --- a/set.go +++ b/set.go @@ -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 diff --git a/set_test.go b/set_test.go index 6595902..ac3ed75 100644 --- a/set_test.go +++ b/set_test.go @@ -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 {