Created
August 22, 2022 17:39
-
-
Save trinhvanminh/ae59347c80f81d841f139693779f45f4 to your computer and use it in GitHub Desktop.
string to color | use for generating color for "TextAvatar" from username: string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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