From f7077ac5c5b7511ece3ef12f426c075270e99e5d Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 11 Feb 2023 17:23:07 +0000 Subject: [PATCH] Add script for coloring text based on its input --- utils/scripts/color-hash.ksh | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 utils/scripts/color-hash.ksh diff --git a/utils/scripts/color-hash.ksh b/utils/scripts/color-hash.ksh new file mode 100644 index 0000000..bc80fcd --- /dev/null +++ b/utils/scripts/color-hash.ksh @@ -0,0 +1,45 @@ +function _color_hash_djb2 +{ + local c h s + s=$1 + h=${2:-5381} + while (( ${#s} > 0 )); do + c=0x${s%${s#??}} + s=${s#??} + h=$(( ((($h << 5) + $h) + $c) & 0xffff )) + done + print $h +} + +function color_hash +{ + local bright flag h n s + + bright=false + while getopts b flag; do + case $flag in + b) bright=true ;; + *) return 1 ;; + esac + done + shift $(($OPTIND - 1)) + + h= + s=$(print -nr "$1" | od -A n -t x1 | tr -d '[:space:]*') + while :; do + h=$(_color_hash_djb2 "$s" $h) + # Avoid modulo bias. + (( $h >= 4 )) && break + done + h=$(( $h % 12 )) + + if $bright; then + # $h < 6 ? 8 + 1 + $h : 8 + 1 + $h - 6 + n=$(( $h + ($h < 6 ? 9 : 3) )) + else + # $h < 6 ? 1 + $h : 8 + 1 + $h - 6 + n=$(( $h + ($h < 6 ? 1 : 3) )) + fi + + tput setaf $n 0 0 2>/dev/null +}