Skip to content

Commit

Permalink
Adding the Keys method to set.Set
Browse files Browse the repository at this point in the history
  • Loading branch information
zostay committed May 28, 2023
1 parent 2608075 commit 32b4ea0
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
WIP TBD

* Added set.Set.Keys method.

v0.1.0 2023-05-27

* Added generic.CountDeltas function.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
8 changes: 8 additions & 0 deletions set/set.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 {
Expand Down
26 changes: 26 additions & 0 deletions set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 32b4ea0

Please sign in to comment.