diff --git a/datastructures/set.go b/datastructures/set.go index 9852847..220ffda 100644 --- a/datastructures/set.go +++ b/datastructures/set.go @@ -13,6 +13,14 @@ func MakeSet[T comparable]() *Set[T] { } } +func MakeSetFromElements[T comparable](elements ...T) *Set[T] { + set := MakeSet[T]() + for _, element := range elements { + set.Add(element) + } + return set +} + func (set *Set[T]) Exists(key T) bool { _, exists := set.container[key] return exists @@ -22,6 +30,12 @@ func (set *Set[T]) Add(key T) { set.container[key] = struct{}{} } +func (set *Set[T]) AddElements(elements ...T) { + for _, element := range elements { + set.Add(element) + } +} + func (set *Set[T]) Remove(key T) error { _, exists := set.container[key] if !exists { diff --git a/datastructures/set_test.go b/datastructures/set_test.go index 25a2fa3..b692cdf 100644 --- a/datastructures/set_test.go +++ b/datastructures/set_test.go @@ -35,3 +35,13 @@ func TestSetToSlice(t *testing.T) { assert.Contains(t, slice, 5) assert.Contains(t, slice, 7) } + +func TestMakeSetFromElements(t *testing.T) { + intSlice := []int{1, 2, 3} + intSet := MakeSetFromElements(intSlice...) + assert.ElementsMatch(t, intSet.ToSlice(), intSlice) + + stringSlice := []string{"frog", "frogger", "froggy"} + stringSet := MakeSetFromElements(stringSlice...) + assert.ElementsMatch(t, stringSet.ToSlice(), stringSlice) +}