From b6979d0594061ea82065ac4bece57bd5cdcc0237 Mon Sep 17 00:00:00 2001 From: wangwenbin Date: Thu, 25 Jan 2024 14:49:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0map=E9=9B=86=E5=90=88?= =?UTF-8?q?=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- map_set/map.go | 36 ++++++++++++++++++++++++++++++++++++ map_set/map_test.go | 16 ++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 map_set/map.go create mode 100644 map_set/map_test.go diff --git a/map_set/map.go b/map_set/map.go new file mode 100644 index 0000000..91cdef3 --- /dev/null +++ b/map_set/map.go @@ -0,0 +1,36 @@ +package map_set + +import ( + "sort" + + "golang.org/x/exp/constraints" +) + +func New[T comparable](slice ...T) map[T]struct{} { + mapSet := make(map[T]struct{}, len(slice)) + for _, element := range slice { + mapSet[element] = struct{}{} + } + return mapSet +} + +func In[T comparable](needle T, haystack map[T]struct{}) bool { + _, exists := haystack[needle] + return exists +} + +func Keys[T comparable](mapSet map[T]struct{}) []T { + slice := make([]T, 0, len(mapSet)) + for k := range mapSet { + slice = append(slice, k) + } + return slice +} + +func Sort[T constraints.Ordered](mapSet map[T]struct{}) []T { + keys := Keys(mapSet) + sort.Slice(keys, func(i, j int) bool { + return keys[i] < keys[j] + }) + return keys +} diff --git a/map_set/map_test.go b/map_set/map_test.go new file mode 100644 index 0000000..35cb681 --- /dev/null +++ b/map_set/map_test.go @@ -0,0 +1,16 @@ +package map_set + +import "testing" + +func TestMapSet(t *testing.T) { + mapSet := New(2, 3, 1, 5, 4) + res := In(3, mapSet) + if !res { + t.Error("In() error") + } + + slice := Sort(mapSet) + if slice[0] != 1 || slice[1] != 2 || slice[2] != 3 || slice[3] != 4 || slice[4] != 5 { + t.Error("Sort() error") + } +}