Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 74c18f1

Browse filesBrowse files
authored
Merge pull request #122 from arnovanliere/feature/stringer-join
Add StringerJoin()
2 parents 4286a07 + 628a1b9 commit 74c18f1
Copy full SHA for 74c18f1

File tree

Expand file treeCollapse file tree

2 files changed

+55
-0
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+55
-0
lines changed

‎join.go

Copy file name to clipboardExpand all lines: join.go
+25Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package funk
22

33
import (
44
"reflect"
5+
"strings"
56
)
67

78
type JoinFnc func(lx, rx reflect.Value) reflect.Value
@@ -84,3 +85,27 @@ func hashSlice(arr reflect.Value) map[interface{}]struct{} {
8485
}
8586
return hash
8687
}
88+
89+
// StringerJoin joins an array of elements which implement the `String() string` function.
90+
// Direct copy of strings.Join() with a few tweaks.
91+
func StringerJoin(elems []interface{ String() string }, sep string) string {
92+
switch len(elems) {
93+
case 0:
94+
return ""
95+
case 1:
96+
return elems[0].String()
97+
}
98+
n := len(sep) * (len(elems) - 1)
99+
for i := 0; i < len(elems); i++ {
100+
n += len(elems[i].String())
101+
}
102+
103+
var b strings.Builder
104+
b.Grow(n)
105+
b.WriteString(elems[0].String())
106+
for _, s := range elems[1:] {
107+
b.WriteString(sep)
108+
b.WriteString(s.String())
109+
}
110+
return b.String()
111+
}

‎join_test.go

Copy file name to clipboardExpand all lines: join_test.go
+30Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,33 @@ func TestJoin_RightJoin(t *testing.T) {
9393
})
9494
}
9595
}
96+
97+
// Struct which implements the String() method to test StringerJoin().
98+
type S struct {
99+
Value string
100+
}
101+
102+
func (s S) String() string {
103+
return s.Value
104+
}
105+
106+
func TestJoin_StringerJoin(t *testing.T) {
107+
testCases := []struct {
108+
Arr []interface{ String() string }
109+
Sep string
110+
Expect string
111+
}{
112+
{[]interface{ String() string }{}, ", ", ""},
113+
{[]interface{ String() string }{S{"foo"}}, ", ", "foo"},
114+
{[]interface{ String() string }{S{"foo"}, S{"bar"}, S{"baz"}}, ", ", "foo, bar, baz"},
115+
}
116+
117+
for idx, tt := range testCases {
118+
t.Run(fmt.Sprintf("test case #%d", idx+1), func(t *testing.T) {
119+
is := assert.New(t)
120+
121+
actual := StringerJoin(tt.Arr, tt.Sep)
122+
is.Equal(tt.Expect, actual)
123+
})
124+
}
125+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.