From 32b4ea027b17fabe4b2409742895377d7a4a5855 Mon Sep 17 00:00:00 2001 From: Sterling Hanenkamp Date: Sun, 28 May 2023 15:25:21 -0500 Subject: [PATCH] Adding the Keys method to set.Set --- Changes.md | 4 ++++ README.md | 1 + set/set.go | 8 ++++++++ set/set_test.go | 26 ++++++++++++++++++++++++++ 4 files changed, 39 insertions(+) diff --git a/Changes.md b/Changes.md index a762b37..6a3dc61 100644 --- a/Changes.md +++ b/Changes.md @@ -1,3 +1,7 @@ +WIP TBD + + * Added set.Set.Keys method. + v0.1.0 2023-05-27 * Added generic.CountDeltas function. diff --git a/README.md b/README.md index 63708fc..625b02e 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ following methods on sets: * `Delete(val)` * `Len()` * `SubsetOf(set)` + * `Keys()` And then it also provides these functions to work on sets: diff --git a/set/set.go b/set/set.go index aa55c46..b9d0a83 100644 --- a/set/set.go +++ b/set/set.go @@ -1,5 +1,7 @@ package set +import "github.com/zostay/go-std/maps" + // Set provides a generic set data type. A set is an unsorted list of objects // where each object is unique, as defined by the equivalence operation. These // are implemented using a map. Any value that can be used as a map key can be @@ -54,6 +56,12 @@ func (s Set[T]) SubsetOf(o Set[T]) bool { return true } +// Keys returns all the keys in the set as a slice. The return slice is +// unsorted and the keys returned could be in any order. +func (s Set[T]) Keys() []T { + return maps.Keys(s) +} + // Intersects returns true if any value in set a is found within set b. func Intersects[T comparable](a, b Set[T]) bool { for val := range a { diff --git a/set/set_test.go b/set/set_test.go index 05e0844..0570a9e 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -108,6 +108,32 @@ func TestSet_SubsetOf(t *testing.T) { assert.True(t, s3.SubsetOf(s3)) } +func TestSet_Keys(t *testing.T) { + s1 := set.New(1, 2, 3) + s2 := set.New(2, 3) + s3 := set.New(3, 4) + s4 := set.New[int]() + + keys := s1.Keys() + assert.Len(t, keys, 3) + assert.Contains(t, keys, 1) + assert.Contains(t, keys, 2) + assert.Contains(t, keys, 3) + + keys = s2.Keys() + assert.Len(t, keys, 2) + assert.Contains(t, keys, 2) + assert.Contains(t, keys, 3) + + keys = s3.Keys() + assert.Len(t, keys, 2) + assert.Contains(t, keys, 3) + assert.Contains(t, keys, 4) + + keys = s4.Keys() + assert.Len(t, keys, 0) +} + func TestDifference(t *testing.T) { s1 := set.New(1, 2, 3) s2 := set.New(3, 4, 5)