Skip to content

Commit

Permalink
util: Random functions for return value and one of arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
gliga committed Aug 15, 2024
1 parent 02be941 commit 1b9fe26
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/util/rand.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions src/util/rand_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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) || \
Expand Down

0 comments on commit 1b9fe26

Please sign in to comment.