Skip to content

Commit 208a228

Browse files
authored
feat: add is empty functionality to set (#133)
1 parent 325f1e0 commit 208a228

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

set.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,9 @@ type Set[T comparable] interface {
9797
// panic.
9898
Intersect(other Set[T]) Set[T]
9999

100+
// IsEmpty determines if there are elements in the set.
101+
IsEmpty() bool
102+
100103
// IsProperSubset determines if every element in this set is in
101104
// the other set but the two sets are not equal.
102105
//

threadsafe.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ func (t *threadSafeSet[T]) ContainsAny(v ...T) bool {
7474
return ret
7575
}
7676

77+
func (t *threadSafeSet[T]) IsEmpty() bool {
78+
return t.Cardinality() == 0
79+
}
80+
7781
func (t *threadSafeSet[T]) IsSubset(other Set[T]) bool {
7882
o := other.(*threadSafeSet[T])
7983

threadsafe_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,29 @@ func Test_IntersectConcurrent(t *testing.T) {
259259
wg.Wait()
260260
}
261261

262+
func Test_IsEmptyConcurrent(t *testing.T) {
263+
runtime.GOMAXPROCS(2)
264+
265+
s := NewSet[int]()
266+
267+
var wg sync.WaitGroup
268+
wg.Add(1)
269+
go func() {
270+
for i := 0; i < N; i++ {
271+
size := s.Cardinality()
272+
if s.IsEmpty() && size > 0 {
273+
t.Errorf("Is Empty should be return false")
274+
}
275+
}
276+
wg.Done()
277+
}()
278+
279+
for i := 0; i < N; i++ {
280+
s.Add(rand.Int())
281+
}
282+
wg.Wait()
283+
}
284+
262285
func Test_IsSubsetConcurrent(t *testing.T) {
263286
runtime.GOMAXPROCS(2)
264287

threadunsafe.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,10 @@ func (s threadUnsafeSet[T]) Intersect(other Set[T]) Set[T] {
163163
return intersection
164164
}
165165

166+
func (s threadUnsafeSet[T]) IsEmpty() bool {
167+
return s.Cardinality() == 0
168+
}
169+
166170
func (s threadUnsafeSet[T]) IsProperSubset(other Set[T]) bool {
167171
return s.Cardinality() < other.Cardinality() && s.IsSubset(other)
168172
}

0 commit comments

Comments
 (0)