From 14fa41721fb577b493836880e01ba8ae85ab7da3 Mon Sep 17 00:00:00 2001 From: yuan Date: Thu, 14 Sep 2023 20:55:27 +0800 Subject: [PATCH 1/2] add Join func --- mr.go | 13 +++++++++++++ mr_test.go | 10 ++++++++++ 2 files changed, 23 insertions(+) diff --git a/mr.go b/mr.go index 6e40aa2..d98e957 100644 --- a/mr.go +++ b/mr.go @@ -1,5 +1,7 @@ package mr +import "strings" + func Map[T any, R any](ts []T, f func(T) R) []R { nt := make([]R, 0, len(ts)) for _, t := range ts { @@ -107,3 +109,14 @@ func Paginate[T any](list []T, page, size int) []T { } return list[offset : offset+size] } + +func Join[T any](list []T, sep string, f func(T) string) string { + var builder strings.Builder + for i := 0; i < len(list); i++ { + if i > 0 { + builder.WriteString(sep) + } + builder.WriteString(f(list[i])) + } + return builder.String() +} diff --git a/mr_test.go b/mr_test.go index 3ee234a..8504c1d 100644 --- a/mr_test.go +++ b/mr_test.go @@ -1,6 +1,7 @@ package mr import ( + "strconv" "testing" "github.com/stretchr/testify/assert" @@ -263,3 +264,12 @@ func TestPaginate(t *testing.T) { result = Paginate(ts, 2, 2) assert.Equal(t, expected, result) } + +func TestJoin(t *testing.T) { + str := Join(test_int_arr, ",", func(i int) string { return strconv.Itoa(i) }) + assert.Equal(t, "1,2,3,4,5", str) + + ts := []int{} + str = Join(ts, ",", func(i int) string { return strconv.Itoa(i) }) + assert.Empty(t, str) +} From a7457ca363af2391e741562d9d17f4f74eb8bbe4 Mon Sep 17 00:00:00 2001 From: yuan Date: Tue, 2 Jan 2024 09:20:20 +0800 Subject: [PATCH 2/2] add keys func --- mr.go | 8 ++++++++ mr_test.go | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/mr.go b/mr.go index d98e957..5a68da0 100644 --- a/mr.go +++ b/mr.go @@ -120,3 +120,11 @@ func Join[T any](list []T, sep string, f func(T) string) string { } return builder.String() } + +func Keys[T any, KEY comparable](data map[KEY]T) []KEY { + var d []KEY + for k := range data { + d = append(d, k) + } + return d +} diff --git a/mr_test.go b/mr_test.go index 8504c1d..b66f80b 100644 --- a/mr_test.go +++ b/mr_test.go @@ -273,3 +273,14 @@ func TestJoin(t *testing.T) { str = Join(ts, ",", func(i int) string { return strconv.Itoa(i) }) assert.Empty(t, str) } + +func TestKeys(t *testing.T) { + td1 := map[string]int64{ + "a": 1, + "b": 2, + "c": 3, + } + actual := Keys(td1) + expected := []string{"a", "b", "c"} + assert.EqualValuesf(t, expected, actual, "Expected %v atutal %v", expected, actual) +}