Skip to content

Instantly share code, notes, and snippets.

@schie
Created February 3, 2018 18:35
Show Gist options
  • Save schie/95479ac8e039dcef5fcc76696c7aea9c to your computer and use it in GitHub Desktop.
Save schie/95479ac8e039dcef5fcc76696c7aea9c to your computer and use it in GitHub Desktop.
Converting a random string to a hex color
function stringTColor(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
let color = '#';
for (let i = 0; i < 3; i++) {
let value = (hash >> (i * 8)) & 0xFF;
color += ('00' + value.toString(16)).substr(-2);
}
return color;
}
stringToColor('greenish') // #9bc63b
stringToColor('test') // #924436
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment