mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-11 08:12:26 +08:00
[feature]<slice>: support random item (#146)
Signed-off-by: o98k-ok <hggend@gmail.com>
This commit is contained in:
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/duke-git/lancet/v2/random"
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
@@ -1229,3 +1230,14 @@ func Partition[T any](slice []T, predicates ...func(item T) bool) [][]T {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Random get a random item of slice, return idx=-1 when slice is empty
|
||||
// Play: todo
|
||||
func Random[T any](slice []T) (val T, idx int) {
|
||||
if len(slice) == 0 {
|
||||
return val, -1
|
||||
}
|
||||
|
||||
idx = random.RandInt(0, len(slice))
|
||||
return slice[idx], idx
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user