Skip to content

Commit

Permalink
Add StringerJoin()
Browse files Browse the repository at this point in the history
Join array of interfaces which implmement the  function. This resolves Issue #121
  • Loading branch information
arnovanliere committed May 5, 2021
1 parent efae847 commit 628a1b9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
25 changes: 25 additions & 0 deletions join.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package funk

import (
"reflect"
"strings"
)

type JoinFnc func(lx, rx reflect.Value) reflect.Value
Expand Down Expand Up @@ -84,3 +85,27 @@ func hashSlice(arr reflect.Value) map[interface{}]struct{} {
}
return hash
}

// StringerJoin joins an array of elements which implement the `String() string` function.
// Direct copy of strings.Join() with a few tweaks.
func StringerJoin(elems []interface{ String() string }, sep string) string {
switch len(elems) {
case 0:
return ""
case 1:
return elems[0].String()
}
n := len(sep) * (len(elems) - 1)
for i := 0; i < len(elems); i++ {
n += len(elems[i].String())
}

var b strings.Builder
b.Grow(n)
b.WriteString(elems[0].String())
for _, s := range elems[1:] {
b.WriteString(sep)
b.WriteString(s.String())
}
return b.String()
}
30 changes: 30 additions & 0 deletions join_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,33 @@ func TestJoin_RightJoin(t *testing.T) {
})
}
}

// Struct which implements the String() method to test StringerJoin().
type S struct {
Value string
}

func (s S) String() string {
return s.Value
}

func TestJoin_StringerJoin(t *testing.T) {
testCases := []struct {
Arr []interface{ String() string }
Sep string
Expect string
}{
{[]interface{ String() string }{}, ", ", ""},
{[]interface{ String() string }{S{"foo"}}, ", ", "foo"},
{[]interface{ String() string }{S{"foo"}, S{"bar"}, S{"baz"}}, ", ", "foo, bar, baz"},
}

for idx, tt := range testCases {
t.Run(fmt.Sprintf("test case #%d", idx+1), func(t *testing.T) {
is := assert.New(t)

actual := StringerJoin(tt.Arr, tt.Sep)
is.Equal(tt.Expect, actual)
})
}
}

0 comments on commit 628a1b9

Please sign in to comment.