Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added nil checks to sets union and intersect operations #50

Merged
merged 1 commit into from
Jan 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions datastructures/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,28 +58,34 @@ func (set *Set[T]) ToSlice() []T {
return slice
}

func (setA *Set[T]) Intersect(setB *Set[T]) *Set[T] {
intersectedSet := MakeSet[T]()
bigSet, smallSet := setB, setA
if setA.Size() > setB.Size() {
bigSet, smallSet = setA, setB
func (set *Set[T]) Intersect(setB *Set[T]) *Set[T] {
intersectSet := MakeSet[T]()
if setB == nil {
return intersectSet
}
bigSet, smallSet := setB, set
if set.Size() > setB.Size() {
bigSet, smallSet = set, setB
}

for key := range smallSet.container {
if bigSet.Exists(key) {
intersectedSet.Add(key)
intersectSet.Add(key)
}
}
return intersectedSet
return intersectSet
}

func (setA *Set[T]) Union(setB *Set[T]) *Set[T] {
unionedSet := MakeSet[T]()
for key := range setA.container {
unionedSet.Add(key)
func (set *Set[T]) Union(setB *Set[T]) *Set[T] {
if setB == nil {
return set
}
unionSet := MakeSet[T]()
for key := range set.container {
unionSet.Add(key)
}
for key := range setB.container {
unionedSet.Add(key)
unionSet.Add(key)
}
return unionedSet
return unionSet
}
Loading