diff --git a/src/util/rand.sh b/src/util/rand.sh index b74dbe6..844d76a 100644 --- a/src/util/rand.sh +++ b/src/util/rand.sh @@ -24,6 +24,32 @@ function rand_bool() { echo $(( ${RANDOM} % 2 )) } +function rand_return() { + # Return (`return`) randomly 0 or 1. This can be convenient to + # use in if statements. + local ctx; is_ctx "${1}" && ctx="${1}" && shift + [ $# -ne 0 ] && { ctx_wn $ctx; return $EC; } + shift 0 || { ctx_wn $ctx; return $EC; } + + # No arguments to check. + + [ $(rand_bool) = 1 ] +} + +function rand_args() { + # Return random argument given to this function. + local ctx; is_ctx "${1}" && ctx="${1}" && shift + [ $# -eq 0 ] && { ctx_wn $ctx; return $EC; } + shift 0 || { ctx_wn $ctx; return $EC; } + + # No arguments to check. + + local vals=( $@ ) + local len=${#vals[@]} + local ix=$(( $RANDOM % len )) + echo "${vals[${ix}]}" +} + function rand_int() { # Generate random int. local ctx; is_ctx "${1}" && ctx="${1}" && shift diff --git a/src/util/rand_test.sh b/src/util/rand_test.sh index 4bc8ffc..b6d4280 100644 --- a/src/util/rand_test.sh +++ b/src/util/rand_test.sh @@ -25,6 +25,24 @@ function test_rand_bool() { } readonly -f test_rand_bool +function test_rand_return() { + [ rand_return ] || return 0 +} +readonly -f test_rand_return + +function test_rand_args() { + local val + val=$(rand_args "one" "two") + + [ "${val}" = "one" -o "${val}" = "two" ] || \ + assert_fail + + rand_args && assert_fail + + return 0 +} +readonly -f test_rand_args + function test_rand_int() { local val val=$(rand_int) || \