feat: add Shuffle func

This commit is contained in:
dudaodong committed 2022-01-01 19:18:33 +08:00
1 parent 042a00296f
commit ed4acc1c67
2 files changed
+24

No files matched your search

+14
View File
@@ -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