aboutsummaryrefslogtreecommitdiff
path: root/bin/clamp
diff options
context:
space:
mode:
Diffstat (limited to 'bin/clamp')
-rwxr-xr-xbin/clamp86
1 files changed, 86 insertions, 0 deletions
diff --git a/bin/clamp b/bin/clamp
new file mode 100755
index 0000000..a673f72
--- /dev/null
+++ b/bin/clamp
@@ -0,0 +1,86 @@
+#!/bin/sh
+set -eu
+
+usage() {
+ cat <<-'EOF'
+ Usage:
+ clamp NUMBER MIN MAX
+ clamp -h
+ EOF
+}
+
+help() {
+ cat <<-'EOF'
+
+ Options:
+ -h, --help show this message
+
+
+ Clamp the NUMBER between MIN and MAX.
+
+
+ Examples:
+
+ Assert the number is within the interval:
+
+ $ clamp 5 3 9
+ 5
+
+ When a number is below MIN it gets clamped:
+
+ $ clamp 1 3 9
+ 3
+
+ When a number is above MAX it gets clamped:
+
+ $ clamp 15 3 9
+ 9
+ EOF
+}
+
+for flag in "$@"; do
+ case "$flag" in
+ --)
+ break
+ ;;
+ --help)
+ usage
+ help
+ exit
+ ;;
+ *)
+ ;;
+ esac
+done
+
+while getopts 'h' flag; do
+ case "$flag" in
+ h)
+ usage
+ help
+ exit
+ ;;
+ *)
+ usage >&2
+ exit 2
+ ;;
+ esac
+done
+shift $((OPTIND - 1))
+
+
+NUMBER="${1:-}"
+MIN="${2:-}"
+MAX="${3:-}"
+
+eval "$(assert-arg "$NUMBER" 'NUMBER')"
+eval "$(assert-arg "$MIN" 'MIN')"
+eval "$(assert-arg "$MAX" 'MAX')"
+
+
+if [ "$MIN" -gt "$MAX" ]; then
+ printf 'MIN (%s) is greater then MAX (%s).\n' "$MIN" "$MAX" >&2
+ exit 2
+fi
+
+min -- "$(max -- "$NUMBER" "$MIN")" "$MAX"