Last active
February 23, 2021 10:22
-
-
Save larchanka/6248783e0b21d37ad02f to your computer and use it in GitHub Desktop.
Function converts string to HEX-color
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
const stringToColor = (str) => { | |
let hash = 0; | |
let color = '#'; | |
let defaultColor = '#333333'; | |
let i; | |
let value; | |
let strLength; | |
if(!str) { | |
return defaultColor; | |
} | |
strLength = str.length; | |
for (i = 0; i < strLength; i++) { | |
hash = str.charCodeAt(i) + ((hash << 5) - hash); | |
} | |
for (i = 0; i < 3; i++) { | |
value = (hash >> (i * 8)) & 0xFF; | |
color += ('00' + value.toString(16)).substr(-2); | |
} | |
return color; | |
}; | |
export default stringToColor; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use: