Skip to content

Commit

Permalink
feat: add is empty functionality to set (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jibaru authored Nov 5, 2023
1 parent 325f1e0 commit 208a228
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ type Set[T comparable] interface {
// panic.
Intersect(other Set[T]) Set[T]

// IsEmpty determines if there are elements in the set.
IsEmpty() bool

// IsProperSubset determines if every element in this set is in
// the other set but the two sets are not equal.
//
Expand Down
4 changes: 4 additions & 0 deletions threadsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ func (t *threadSafeSet[T]) ContainsAny(v ...T) bool {
return ret
}

func (t *threadSafeSet[T]) IsEmpty() bool {
return t.Cardinality() == 0
}

func (t *threadSafeSet[T]) IsSubset(other Set[T]) bool {
o := other.(*threadSafeSet[T])

Expand Down
23 changes: 23 additions & 0 deletions threadsafe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,29 @@ func Test_IntersectConcurrent(t *testing.T) {
wg.Wait()
}

func Test_IsEmptyConcurrent(t *testing.T) {
runtime.GOMAXPROCS(2)

s := NewSet[int]()

var wg sync.WaitGroup
wg.Add(1)
go func() {
for i := 0; i < N; i++ {
size := s.Cardinality()
if s.IsEmpty() && size > 0 {
t.Errorf("Is Empty should be return false")
}
}
wg.Done()
}()

for i := 0; i < N; i++ {
s.Add(rand.Int())
}
wg.Wait()
}

func Test_IsSubsetConcurrent(t *testing.T) {
runtime.GOMAXPROCS(2)

Expand Down
4 changes: 4 additions & 0 deletions threadunsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,10 @@ func (s threadUnsafeSet[T]) Intersect(other Set[T]) Set[T] {
return intersection
}

func (s threadUnsafeSet[T]) IsEmpty() bool {
return s.Cardinality() == 0
}

func (s threadUnsafeSet[T]) IsProperSubset(other Set[T]) bool {
return s.Cardinality() < other.Cardinality() && s.IsSubset(other)
}
Expand Down

0 comments on commit 208a228

Please sign in to comment.