Skip to content

Commit 1b9fe26

Browse files
committed
util: Random functions for return value and one of arguments
1 parent 02be941 commit 1b9fe26

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/util/rand.sh

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,32 @@ function rand_bool() {
2424
echo $(( ${RANDOM} % 2 ))
2525
}
2626

27+
function rand_return() {
28+
# Return (`return`) randomly 0 or 1. This can be convenient to
29+
# use in if statements.
30+
local ctx; is_ctx "${1}" && ctx="${1}" && shift
31+
[ $# -ne 0 ] && { ctx_wn $ctx; return $EC; }
32+
shift 0 || { ctx_wn $ctx; return $EC; }
33+
34+
# No arguments to check.
35+
36+
[ $(rand_bool) = 1 ]
37+
}
38+
39+
function rand_args() {
40+
# Return random argument given to this function.
41+
local ctx; is_ctx "${1}" && ctx="${1}" && shift
42+
[ $# -eq 0 ] && { ctx_wn $ctx; return $EC; }
43+
shift 0 || { ctx_wn $ctx; return $EC; }
44+
45+
# No arguments to check.
46+
47+
local vals=( $@ )
48+
local len=${#vals[@]}
49+
local ix=$(( $RANDOM % len ))
50+
echo "${vals[${ix}]}"
51+
}
52+
2753
function rand_int() {
2854
# Generate random int.
2955
local ctx; is_ctx "${1}" && ctx="${1}" && shift

src/util/rand_test.sh

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,24 @@ function test_rand_bool() {
2525
}
2626
readonly -f test_rand_bool
2727

28+
function test_rand_return() {
29+
[ rand_return ] || return 0
30+
}
31+
readonly -f test_rand_return
32+
33+
function test_rand_args() {
34+
local val
35+
val=$(rand_args "one" "two")
36+
37+
[ "${val}" = "one" -o "${val}" = "two" ] || \
38+
assert_fail
39+
40+
rand_args && assert_fail
41+
42+
return 0
43+
}
44+
readonly -f test_rand_args
45+
2846
function test_rand_int() {
2947
local val
3048
val=$(rand_int) || \

0 commit comments

Comments
 (0)