Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: Random functions for return value and one of arguments #25

Merged
merged 1 commit into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading