Skip to content

Commit

Permalink
go back to comparable for base type, make Sort a function as a result
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Feb 21, 2023
1 parent 6e71e60 commit 3d9ba3c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
12 changes: 6 additions & 6 deletions sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import (
"golang.org/x/exp/constraints"
)

type Set[T constraints.Ordered] map[T]struct{}
type Set[T comparable] map[T]struct{}

// SetFromSlice constructs a Set from a slice.
func FromSlice[T constraints.Ordered](items []T) Set[T] {
func FromSlice[T comparable](items []T) Set[T] {
// best pre-allocation if there are no duplicates
res := make(map[T]struct{}, len(items))
for _, item := range items {
Expand Down Expand Up @@ -52,7 +52,7 @@ func (s Set[T]) Remove(item ...T) {
}
}

func New[T constraints.Ordered](item ...T) Set[T] {
func New[T comparable](item ...T) Set[T] {
res := make(Set[T], len(item))
res.Add(item...)
return res
Expand All @@ -70,7 +70,7 @@ func (s Set[T]) String() string {
// RemoveCommon removes elements from both sets that are in both,
// leaving only the delta. Useful for Notifier on Set so that
// oldValue has what has been removed and newValue has what has been added.
func RemoveCommon[T constraints.Ordered](a, b Set[T]) {
func RemoveCommon[T comparable](a, b Set[T]) {
if len(a) > len(b) {
a, b = b, a
}
Expand All @@ -82,8 +82,8 @@ func RemoveCommon[T constraints.Ordered](a, b Set[T]) {
}
}

func (s Set[T]) Sorted() []T {
keys := make([]T, 0, len(s))
func Sort[Q constraints.Ordered](s Set[Q]) []Q {
keys := make([]Q, 0, len(s))
for k := range s {
keys = append(keys, k)
}
Expand Down
2 changes: 1 addition & 1 deletion sets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestArrayToSet(t *testing.T) {
a := []string{"z", "a", "c", "b"}
s := sets.FromSlice(a)
assert.Equal(t, "a,b,c,z", s.String())
assert.Equal(t, s.Sorted(), []string{"a", "b", "c", "z"})
assert.Equal(t, sets.Sort(s), []string{"a", "b", "c", "z"})
}

func TestRemoveCommon(t *testing.T) {
Expand Down

0 comments on commit 3d9ba3c

Please sign in to comment.