-
-
Save ScoreUnder/5c4ec438e9fd9caffa76a9742dec2b87 to your computer and use it in GitHub Desktop.
Naive hash code functions for creating terminal colours
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/busybox sh | |
# Original code, slow, not sh-compatible | |
hashcode() { | |
local hash=0 | |
local str="$1"X | |
while [ -n "$str" ]; do | |
ch="${str:0:1}" | |
hash=$(( ($hash * 173 + $(printf '%d' "'$ch")) % 256 )) | |
str="${str:1}" | |
done | |
printf %s "$hash" | |
} | |
printf "\033[38;5;%sm%s\n" "$(hashcode "$1")" "$1" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# Perl version, the fastest (because of course it is) | |
sub hashcode { | |
my ($str) = @_; | |
$str .= 'X'; | |
my $hash = 0; | |
for (0..(length($str) - 1)) { | |
$hash = ($hash * 173 + ord(substr($str, $_, 1))) & 0xFF; | |
} | |
$hash | |
} | |
$/ = ''; | |
my $str = <>; | |
chomp $str; | |
printf "\033[38;5;%sm%s\n", hashcode($str), $str; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
hashcode() { | |
local hash=0 | |
local str="$1"X | |
set -- | |
while [ -n "$str" ]; do | |
next_str=${str#?} | |
ch=${str%"$next_str"} | |
set -- "$@" "'$ch" | |
str=$next_str | |
done | |
for n in $(printf '%d ' "$@"); do | |
hash=$(( (hash * 173 + n) % 256 )) | |
done | |
printf %s "$hash" | |
} | |
contents=$(cat) | |
printf "\033[38;5;%sm%s\n" "$(hashcode "$contents")" "$contents" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also there isn't a warranty or anything like that :^)