making set more generic
This commit is contained in:
parent
a2858cb3dc
commit
4ea82a9ed2
15
set.go
15
set.go
@ -2,14 +2,11 @@ package set
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"sort"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
type Set[T constraints.Ordered] map[T]struct{}
|
||||
type Set[T comparable] map[T]struct{}
|
||||
|
||||
func New[T constraints.Ordered](elements ...T) Set[T] {
|
||||
func New[T comparable](elements ...T) Set[T] {
|
||||
s := Set[T]{}
|
||||
for _, e := range elements {
|
||||
s.Add(e)
|
||||
@ -46,14 +43,6 @@ func (s Set[T]) ToSlice() []T {
|
||||
return elements
|
||||
}
|
||||
|
||||
func (s Set[T]) ToSortedSlice() []T {
|
||||
elements := s.ToSlice()
|
||||
sort.Slice(elements, func(i, j int) bool {
|
||||
return elements[i] < elements[j]
|
||||
})
|
||||
return elements
|
||||
}
|
||||
|
||||
func (s Set[T]) Union(other Set[T]) Set[T] {
|
||||
result := New[T]()
|
||||
for e := range s {
|
||||
|
||||
12
set_test.go
12
set_test.go
@ -194,15 +194,3 @@ func TestToSlice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestToSortedSlice(t *testing.T) {
|
||||
s := New[int](3, 1, 2)
|
||||
want := []int{1, 2, 3}
|
||||
got := s.ToSortedSlice()
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("ToSortedSlice() = %v; want %v", got, want)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user