Skip to content

Commit

Permalink
✨ feat: Slice converts a string to a slice
Browse files Browse the repository at this point in the history
  • Loading branch information
sohaha committed Sep 12, 2024
1 parent 3ac0f6c commit 245ccba
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
17 changes: 17 additions & 0 deletions zarray/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ package zarray

import (
"math/rand"
"strings"

"github.com/sohaha/zlsgo/zstring"
"github.com/sohaha/zlsgo/zsync"
"github.com/sohaha/zlsgo/ztype"
"github.com/sohaha/zlsgo/zutil"
)

Expand Down Expand Up @@ -195,3 +197,18 @@ func Shift[T comparable](list *[]T) (v T) {
*list = (*list)[1:]
return
}

// Slice converts a string to a slice.
func Slice[T comparable](s string) []T {
if s == "" {
return []T{}
}

ss := strings.Split(s, ",")
res := make([]T, len(ss))
for i := range ss {
ztype.To(zstring.TrimSpace(ss[i]), &res[i])
}

return res
}
14 changes: 12 additions & 2 deletions zarray/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import (
"github.com/sohaha/zlsgo/ztype"
)

var l = []int{0, 1, 2, 3, 4, 5}
var l2 = []int{0, 1, 2, 3, 4, 5, 2, 34, 5, 6, 7, 98, 6, 67, 54, 543, 345, 435, 43543, 435, 3, 2, 42, 3423, 54, 6, 5}
var (
l = []int{0, 1, 2, 3, 4, 5}
l2 = []int{0, 1, 2, 3, 4, 5, 2, 34, 5, 6, 7, 98, 6, 67, 54, 543, 345, 435, 43543, 435, 3, 2, 42, 3423, 54, 6, 5}
)

func TestShuffle(t *testing.T) {
t.Log(zarray.Shuffle(l))
Expand Down Expand Up @@ -128,3 +130,11 @@ func TestFind(t *testing.T) {
tt.EqualTrue(!ok)
tt.Equal("", v["name"])
}

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([]int{}, zarray.Slice[int](""))
}

0 comments on commit 245ccba

Please sign in to comment.