Skip to content

Commit

Permalink
sets: provide an Empty() method (#15)
Browse files Browse the repository at this point in the history
This PR expands Set and HashSet to implement an Empty() method. The method
returns true if a set is empty, false otherwise. This will help cleanup some
lines of code where we other wise need to do something like .Size() == 0.
  • Loading branch information
shoenig authored Dec 5, 2022
1 parent e54751d commit 7c18a96
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Implements the following set operations
- ContainsAll
- Subset
- Size
- Empty
- Union
- Difference
- Intersect
Expand Down
5 changes: 5 additions & 0 deletions hashset.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ func (s *HashSet[T, H]) Size() int {
return len(s.items)
}

// Empty returns true if s contains no elements, false otherwise.
func (s *HashSet[T, H]) Empty() bool {
return s.Size() == 0
}

// Union returns a set that contains all elements of s and o combined.
func (s *HashSet[T, H]) Union(o *HashSet[T, H]) *HashSet[T, H] {
result := NewHashSet[T, H](s.Size())
Expand Down
14 changes: 14 additions & 0 deletions hashset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,20 @@ func TestHashSet_Size(t *testing.T) {
})
}

func TestHashSet_Empty(t *testing.T) {
t.Run("is empty", func(t *testing.T) {
s := NewHashSet[*company, string](10)
must.Empty(t, s)
})

t.Run("is not empty", func(t *testing.T) {
s := NewHashSet[*company, string](10)
must.True(t, s.Insert(c1))
must.True(t, s.Insert(c2))
must.NotEmpty(t, s)
})
}

func TestHashSet_Difference(t *testing.T) {
t.Run("empty \\ empty", func(t *testing.T) {
a := NewHashSet[*company, string](10)
Expand Down
5 changes: 5 additions & 0 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@ func (s *Set[T]) Size() int {
return len(s.items)
}

// Empty returns true if s contains no elements, false otherwise.
func (s *Set[T]) Empty() bool {
return s.Size() == 0
}

// Union returns a set that contains all elements of s and o combined.
func (s *Set[T]) Union(o *Set[T]) *Set[T] {
result := New[T](s.Size())
Expand Down
12 changes: 12 additions & 0 deletions set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,18 @@ func TestSet_Size(t *testing.T) {
})
}

func TestSet_Empty(t *testing.T) {
t.Run("is empty", func(t *testing.T) {
s := New[int](10)
must.Empty(t, s)
})

t.Run("is not empty", func(t *testing.T) {
s := From[int]([]int{1, 2, 3, 4})
must.NotEmpty(t, s)
})
}

func TestSet_Union(t *testing.T) {
t.Run("empty ∪ empty", func(t *testing.T) {
a := New[int](0)
Expand Down

0 comments on commit 7c18a96

Please sign in to comment.