Created
January 8, 2022 10:23
-
-
Save ViktorReib/4b472eddf467dd08aea9087e23497422 to your computer and use it in GitHub Desktop.
Generate Gravatar or default to Initials Avatar
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
class Avatar { | |
colors = ['#F59C0F', '#009FD4', '#B381B3', '#E3BC00', '#D47500', '#DC2A2A', '#0027D7', "#00B4FF", "#107C10"]; | |
getInitials(fullName: string): string { | |
// remove domain if exists | |
if (fullName.lastIndexOf('@') > 0) { | |
fullName = fullName.substring(0, fullName.lastIndexOf('@')); | |
} | |
// replace '.' with spaces and split the string | |
const allNames = fullName.trim().replace('.', ' ').split(' '); | |
if (allNames.length === 1) { | |
let name = allNames[0]; | |
if (name.length === 0) { | |
return ''; | |
} | |
if (name.length === 1) { | |
return name.charAt(0).toUpperCase(); | |
} | |
if (name.length > 1) { | |
return name.charAt(0).toUpperCase() + name.charAt(1).toUpperCase(); | |
} | |
} | |
return allNames.reduce((acc, curr, index) => { | |
if (index === 0 || index === allNames.length - 1) { | |
acc = `${acc}${curr.charAt(0).toUpperCase()}`; | |
} | |
return acc; | |
}, ''); | |
} | |
getImage(fullName: string) { | |
return this.colors[this.numberFromText(this.getInitials(fullName))]; | |
} | |
numberFromText(text: any): number { | |
let sum = 0; | |
for (let index in text) { | |
sum += text.charCodeAt(index); | |
} | |
return sum % this.colors.length; | |
} | |
} | |
let avatar = new Avatar(); | |
console.log(avatar.getImage('Viktor Reib')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment