1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 16:22:26 +08:00

feat: add Shuffle func

This commit is contained in:
dudaodong
2022-01-01 19:18:33 +08:00
parent 042a00296f
commit ed4acc1c67
2 changed files with 24 additions and 0 deletions

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