[feature]<slice>: support random item (#146)

Signed-off-by: o98k-ok <hggend@gmail.com>
This commit is contained in:
o98k authored and GitHub committed 2023-11-22 16:51:37 +08:00
1 parent 31c618c187
commit 3802c715c3
5 files changed
+109

No files matched your search

+12
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
}