Here's an adaptation of CD Sanchez' answer that consistently returns a 6-digit colour code:
const stringToColour = (str: string) => {
constlet hash = 0;
str.split('').forEach(char => {
hash = char.charCodeAt(0) + ((hash << 5) - hash)
})
let colour = '#'
for (let i = 0; i < 3; i++) {
const value = (hash >> (i * 8)) & 0xff
colour += value.toString(16).padStart(2, '0')
}
return colour
}
If you are using Eslint, you want to wrap this function in the
/* eslint-disable no-bitwise */
>> stringToColour func. definition here" <<
/* eslint-enable no-bitwise */
Usage:
stringToColour("greenish");
// -> #9bc63b
Example:
(An alternative/simpler solution might involve returning an 'rgb(...)'-style colour code.)