Add script for coloring text based on its input

This commit is contained in:
Lucas 2023-02-11 17:23:07 +00:00
parent 8e24da6bcd
commit f7077ac5c5
1 changed files with 45 additions and 0 deletions

View File

@ -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
}