Skip to content

Commit

Permalink
add Join func
Browse files Browse the repository at this point in the history
  • Loading branch information
lyuangg committed Sep 14, 2023
1 parent c12a0f9 commit 14fa417
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions mr.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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()
}
10 changes: 10 additions & 0 deletions mr_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mr

import (
"strconv"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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)
}

0 comments on commit 14fa417

Please sign in to comment.