Skip to content

Instantly share code, notes, and snippets.

@trinhvanminh
Created August 22, 2022 17:39
Show Gist options
  • Save trinhvanminh/ae59347c80f81d841f139693779f45f4 to your computer and use it in GitHub Desktop.
Save trinhvanminh/ae59347c80f81d841f139693779f45f4 to your computer and use it in GitHub Desktop.
string to color | use for generating color for "TextAvatar" from username: string
function stringToColor(string) {
let hash = 0;
let i;
for (i = 0; i < string.length; i += 1) {
hash = string.charCodeAt(i) + ((hash << 5) - hash);
}
let color = '#';
for (i = 0; i < 3; i += 1) {
const value = (hash >> (i * 8)) & 0xff;
color += `00${value.toString(16)}`.slice(-2);
}
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment