Skip to content

Instantly share code, notes, and snippets.

@nixjs
Created November 4, 2022 13:10
Show Gist options
  • Save nixjs/c41307264283bff33cdb5f2b3ca3679a to your computer and use it in GitHub Desktop.
Save nixjs/c41307264283bff33cdb5f2b3ca3679a to your computer and use it in GitHub Desktop.
Generate color by name
export function getColor(name: string): string {
const firstAlphabet = name.charAt(0).toLowerCase()
// get the ASCII code of the character
const asciiCode = firstAlphabet.charCodeAt(0)
// number that contains 3 times ASCII value of character -- unique for every alphabet
const colorNum = asciiCode.toString() + asciiCode.toString() + asciiCode.toString()
const num = Math.round(0xffffff * parseInt(colorNum))
const prefix = (num >> 16) & 255
switch (true) {
case prefix > 0 && prefix <= 45:
return '#F29B4C'
case prefix > 45 && prefix <= 95:
return '#FFD661'
case prefix > 95 && prefix <= 145:
return '#2DB84C'
case prefix > 145 && prefix <= 180:
return '#21D6AA'
case prefix > 180 && prefix <= 240:
return '#22A1D3'
case prefix > 240 && prefix <= 310:
return '#AE56D8'
case prefix > 310 && prefix <= 340:
return '#EF549B'
case prefix > 340 && prefix <= 360:
return '#F25A5A'
default:
return '#F25A5A'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment