From 2b79866b14c07f9cabde96e009f7188db88c42cd Mon Sep 17 00:00:00 2001 From: nikkiing <1031497516@qq.com> Date: Thu, 1 Feb 2024 16:14:06 +0800 Subject: [PATCH] set --- pkg/set/set.go | 48 ++++++++++++++++++++++++++++++++++++++++++--- pkg/set/set_test.go | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 pkg/set/set_test.go diff --git a/pkg/set/set.go b/pkg/set/set.go index bcd6099..c16abac 100644 --- a/pkg/set/set.go +++ b/pkg/set/set.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 +} diff --git a/pkg/set/set_test.go b/pkg/set/set_test.go new file mode 100644 index 0000000..cfaa76c --- /dev/null +++ b/pkg/set/set_test.go @@ -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) + } + }) + } +}