mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Shuffle func
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user