1
0
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:
o98k
2023-11-22 16:51:37 +08:00
committed by GitHub
parent 31c618c187
commit 3802c715c3
5 changed files with 109 additions and 0 deletions

View File

@@ -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
}