nikkiing 11 months ago
parent 62a894e89e
commit 2b79866b14
  1. 48
      pkg/set/set.go
  2. 37
      pkg/set/set_test.go

@ -1,12 +1,30 @@
package set
type Set[T comparable] map[T]struct{}
import "sort"
func NewSet[T comparable]() Set[T] {
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Float interface {
~float32 | ~float64
}
type String interface {
~string
}
type Comparable interface {
Integer | Float | String
}
type Set[T Comparable] map[T]struct{}
func NewSet[T Comparable]() Set[T] {
return make(map[T]struct{})
}
func NewSetWithItems[T comparable](items ...T) Set[T] {
func NewSetWithItems[T Comparable](items ...T) Set[T] {
s := make(Set[T])
s.AddWithOutEmpty(items...)
return s
@ -48,3 +66,27 @@ func (s Set[T]) ToSlice() []T {
}
return res
}
func (s Set[T]) ToSortSlice() []T {
res := make([]T, 0, len(s))
for k := range s {
res = append(res, k)
}
sort.Slice(res, func(i, j int) bool {
return res[i] < res[j]
})
return res
}
func (s Set[T]) ToCustomSortSlice(f func(i, j int) bool) []T {
res := make([]T, 0, len(s))
for k := range s {
res = append(res, k)
}
sort.Slice(res, func(i, j int) bool {
return f(i, j)
})
return res
}

@ -0,0 +1,37 @@
package set
import (
"reflect"
"testing"
)
func TestSet_ToCustomSortSlice(t *testing.T) {
type args struct {
f func(i, j int) bool
}
type testCase[T Comparable] struct {
name string
s Set[T]
args args
want []T
}
tests := []testCase[int]{
{
name: "test1",
s: NewSetWithItems(1, 2, 3, 4, 5),
args: args{
f: func(i, j int) bool {
return i > j
},
},
want: []int{5, 4, 3, 2, 1},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.s.ToCustomSortSlice(tt.args.f); !reflect.DeepEqual(got, tt.want) {
t.Errorf("ToCustomSortSlice() = %v, want %v", got, tt.want)
}
})
}
}
Loading…
Cancel
Save