diff --git a/slice/slice.go b/slice/slice.go index 58e5668..269c0c8 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "math" + "math/rand" "reflect" "sort" "strings" @@ -552,6 +553,19 @@ func ReverseSlice(slice interface{}) { } } +// Shuffle creates an slice of shuffled values +func Shuffle(slice interface{}) interface{} { + sv := sliceValue(slice) + length := sv.Len() + + res := reflect.MakeSlice(sv.Type(), length, length) + for i, v := range rand.Perm(length) { + res.Index(i).Set(sv.Index(v)) + } + + return res.Interface() +} + // SortByField return sorted slice by field // Slice element should be struct, field type should be int, uint, string, or bool // default sortType is ascending (asc), if descending order, set sortType to desc diff --git a/slice/slice_test.go b/slice/slice_test.go index a60796a..690f6f2 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -559,3 +559,13 @@ func TestWithout(t *testing.T) { t.FailNow() } } + +func TestShuffle(t *testing.T) { + s := []int{1, 2, 3, 4, 5} + res := Shuffle(s) + + if reflect.TypeOf(s) != reflect.TypeOf(res) { + internal.LogFailedTestInfo(t, "Shuffle", s, res, res) + t.FailNow() + } +}