Skip to content

Commit

Permalink
🔧 refactor: Update Slice function to accept custom separator
Browse files Browse the repository at this point in the history
  • Loading branch information
sohaha committed Dec 25, 2024
1 parent 638a155 commit 7dfd3d1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
20 changes: 14 additions & 6 deletions zarray/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,36 @@ import (
)

// Slice converts a string to a slice.
// If n is not empty, the string will be split into n parts.
func Slice[T comparable](s string, n ...int) []T {
// If value is not empty, the string will be split into value parts.
func Slice[T comparable](s, sep string, n ...int) []T {
if s == "" {
return []T{}
}

var ss []string
if len(n) > 0 {
ss = strings.SplitN(s, ",", n[0])
ss = strings.SplitN(s, sep, n[0])
} else {
ss = strings.Split(s, ",")
ss = strings.Split(s, sep)
}
res := make([]T, len(ss))
ni := make([]uint32, 0, len(ss))
for i := range ss {
ztype.To(zstring.TrimSpace(ss[i]), &res[i])
if v := zstring.TrimSpace(ss[i]); v != "" {
ztype.To(v, &res[i])
} else {
ni = append(ni, uint32(i))
}
}

for i := range ni {
res = append(res[:ni[i]], res[ni[i]+1:]...)
}
return res
}

// Join slice to string.
// If n is not empty, the string will be split into n parts.
// If value is not empty, the string will be split into value parts.
func Join[T comparable](s []T, sep string) string {
if len(s) == 0 {
return ""
Expand Down
10 changes: 5 additions & 5 deletions zarray/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ import (

func TestSlice(t *testing.T) {
tt := zlsgo.NewTest(t)
tt.Equal([]string{"a", "b", "c"}, zarray.Slice[string]("a,b,c"))
tt.Equal([]int{1, 2, 3}, zarray.Slice[int]("1,2,3"))
tt.Equal([]float64{1.1, 2.2, 3.3}, zarray.Slice[float64]("1.1,2.2,3.3"))
tt.Equal([]string{"1.1", "2.2,3.3"}, zarray.Slice[string]("1.1,2.2,3.3", 2))
tt.Equal([]int{}, zarray.Slice[int](""))
tt.Equal([]string{"a", "b", "c"}, zarray.Slice[string]("a,b,c", ","))
tt.Equal([]int{1, 2, 3}, zarray.Slice[int]("1,2,3", ","))
tt.Equal([]float64{1.1, 2.2, 3.3}, zarray.Slice[float64]("1.1,2.2,3.3", ","))
tt.Equal([]string{"1.1", "2.2,3.3"}, zarray.Slice[string]("1.1,2.2,3.3", ",", 2))
tt.Equal([]int{}, zarray.Slice[int]("", ","))
}

func TestJoin(t *testing.T) {
Expand Down

0 comments on commit 7dfd3d1

Please sign in to comment.