mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add RandFromGivenSlice function (#235)
* feat: add RandFromGivenSlice function * feat: add RandFromGivenSlice function
This commit is contained in:
@@ -185,6 +185,15 @@ func RandStringSlice(charset string, sliceLen, strLen int) []string {
|
||||
return result
|
||||
}
|
||||
|
||||
// RandFromGivenSlice generate a random element from given slice.
|
||||
func RandFromGivenSlice[T any](slice []T) T {
|
||||
if len(slice) == 0 {
|
||||
var zero T
|
||||
return zero
|
||||
}
|
||||
return slice[rand.Intn(len(slice))]
|
||||
}
|
||||
|
||||
// RandUpper generate a random upper case string of specified length.
|
||||
// Play: https://go.dev/play/p/29QfOh0DVuh
|
||||
func RandUpper(length int) string {
|
||||
|
||||
@@ -43,6 +43,24 @@ func ExampleRandString() {
|
||||
// 6
|
||||
}
|
||||
|
||||
func ExampleRandFromGivenSlice() {
|
||||
goods := []string{"apple", "banana", "cherry", "elderberry", "fig", "grape", "honeydew", "kiwi", "lemon",
|
||||
"mango", "nectarine", "orange"}
|
||||
|
||||
isInGoods := false
|
||||
result := RandFromGivenSlice(goods)
|
||||
for _, good := range goods {
|
||||
if good == result {
|
||||
isInGoods = true
|
||||
break
|
||||
}
|
||||
}
|
||||
fmt.Println(isInGoods)
|
||||
|
||||
// Output:
|
||||
// true
|
||||
}
|
||||
|
||||
func ExampleRandUpper() {
|
||||
pattern := `^[A-Z]+$`
|
||||
reg := regexp.MustCompile(pattern)
|
||||
|
||||
@@ -269,6 +269,29 @@ func TestRandStringSlice(t *testing.T) {
|
||||
// })
|
||||
}
|
||||
|
||||
func TestRandFromGivenSlice(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert := internal.NewAssert(t, "TestRandFromGivenSlice")
|
||||
|
||||
randomSet := []any{"a", 8, "王", true, 1.1}
|
||||
result := RandFromGivenSlice(randomSet)
|
||||
find := false
|
||||
for _, v := range randomSet {
|
||||
if v == result {
|
||||
find = true
|
||||
}
|
||||
}
|
||||
assert.Equal(true, find)
|
||||
|
||||
emptyAnyRandomSet := []any{}
|
||||
emptyAnyResult := RandFromGivenSlice(emptyAnyRandomSet)
|
||||
assert.IsNil(emptyAnyResult)
|
||||
|
||||
emptyIntRandomSet := []int{}
|
||||
emtpyIntResult := RandFromGivenSlice(emptyIntRandomSet)
|
||||
assert.Equal(0, emtpyIntResult)
|
||||
}
|
||||
|
||||
func TestRandBool(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert := internal.NewAssert(t, "TestRandBool")
|
||||
|
||||
Reference in New Issue
Block a user