Skip to content

Instantly share code, notes, and snippets.

@ARolek
Created July 20, 2017 21:36
Show Gist options
  • Save ARolek/0efe6098e5b446aa0a546747d0240848 to your computer and use it in GitHub Desktop.
Save ARolek/0efe6098e5b446aa0a546747d0240848 to your computer and use it in GitHub Desktop.
Golang StringToColor
package main
import (
"fmt"
"strconv"
)
// port of https://stackoverflow.com/questions/3426404/create-a-hexadecimal-colour-based-on-a-string-with-javascript
func StringToColor(str string) string {
var hash uint
for i := range []rune(str) {
hash = uint(str[i]) + ((hash << 5) - hash)
}
var color string
for i := 0; i < 3; i++ {
value := (hash >> (uint(i) * 8)) & 0xFF
val := "00" + strconv.FormatUint(uint64(value), 16)
color += val[len(val)-2:]
}
return "#" + color
}
func main() {
fmt.Println(stringToColor("admin_countries_3-7"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment