The script is to colorize nicks on IRC.
Here is the JavaScript:
<script type="text/javascript">
function clean_nick(nick) {
nick = nick.toLowerCase();
nick = nick.replace(/[^a-z]/g, "")
return nick;
}
function hash(nick) {
var cleaned = clean_nick(nick);
var h = 0;
for(var i = 0; i < cleaned.length; i++) {
var a = cleaned.charCodeAt(i)
var b = (h << 6)
var c = (h << 16)
var d = h
h = a + b + c - d;
}
console.log(h);
return h;
}
function get_color(nick) {
var nickhash = hash(nick);
var deg = nickhash % 360;
var h = deg < 0 ? 360 + deg : deg;
var l = 50;
if(h >= 30 && h <= 210) {
l = 30;
}
var s = 20 + Math.abs(nickhash) % 80;
return "hsl(" + h + "," + s + "%," + l + "%)";
}
console.log(get_color("kIrb-839432-`~#$%^&*()_+{}|:<>?/,'.;[]=-_-"));
</script>
And here is a Swift playground:
//: Playground - noun: a place where people can play
import UIKit
extension Character {
func unicodeScalarCodePoint() -> UInt32 {
let characterString = String(self)
let scalars = characterString.unicodeScalars
return scalars[scalars.startIndex].value
}
}
func cleanNick(nick: String) -> String {
let lowerCaseNick = nick.lowercased()
let noNumberNick = lowerCaseNick.components(separatedBy: CharacterSet.decimalDigits).joined()
let noPunctuationNick = noNumberNick.components(separatedBy: CharacterSet.punctuationCharacters).joined()
let noSymbolNick = noPunctuationNick.components(separatedBy: CharacterSet.symbols).joined()
let finishedNick = noSymbolNick.replacingOccurrences(of: " ", with: "")
return finishedNick
}
func hash(nick: String) -> Int {
let cleaned = cleanNick(nick: nick)
var h = 0
for char in cleaned {
let a = char.unicodeScalarCodePoint()
let b = (h << 6)
let c = (h << 16)
let d = h
h = Int(Int(a) + Int(b) + Int(c) - Int(d))
}
print(h)
return h
}
func coloredNick(nick: String) -> String {
let nickHash = hash(nick: nick)
let deg = nickHash % 360
let h = deg < 0 ? 360 + deg : deg
var l = 50
if (h >= 30 && h <= 210) {
l = 30
}
let s = 20 + abs(nickHash) % 80
return "hsl(\(h),\(s),\(l))"
}
print(coloredNick(nick: "kIrb-839432-`~#$%^&*()_+{}|:<>?/,'.;[]=-_-"))
Both should output the same hash, and therefore should output the same hsl(), but something is going wrong in the calculation. Can't figure out where it's going wrong but the hash isn't calculating properly.
Any help is greatly appreciated.