Skip to content

Instantly share code, notes, and snippets.

@ScoreUnder
Created September 19, 2016 09:08
Show Gist options
  • Save ScoreUnder/5c4ec438e9fd9caffa76a9742dec2b87 to your computer and use it in GitHub Desktop.
Save ScoreUnder/5c4ec438e9fd9caffa76a9742dec2b87 to your computer and use it in GitHub Desktop.
Naive hash code functions for creating terminal colours
#!/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"
#!/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;
#!/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"
@ScoreUnder
Copy link
Author

Using a lovely non-OSI-approved(?) license

        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 
                    Version 2, December 2004 

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> 

 Everyone is permitted to copy and distribute verbatim or modified 
 copies of this license document, and changing it is allowed as long 
 as the name is changed. 

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 

  0. You just DO WHAT THE FUCK YOU WANT TO.

@ScoreUnder
Copy link
Author

Also there isn't a warranty or anything like that :^)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment