To convert a String to a cumulative number:
const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0);
console.log(stringToSum("A")); // 65
console.log(stringToSum("Roko")); // 411
console.log(stringToSum("Stack Overflow")); // 1386
_x000D_
Say you want to generate different background colors depending on a username:
const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0);
const UI_userIcon = user => {
const hue = (stringToSum(user.name) - 65) % 360; // "A" = hue: 0
console.log(`Hue: ${hue}`);
return `<div class="UserIcon" style="background:hsl(${hue}, 80%, 60%)" title="${user.name}">
<span class="UserIcon-letter">${user.name[0].toUpperCase()}</span>
</div>`;
};
[
{name:"A"},
{name:"Amanda"},
{name:"amanda"},
{name:"Anna"},
].forEach(user => {
document.body.insertAdjacentHTML("beforeend", UI_userIcon(user));
});
_x000D_
.UserIcon {
width: 4em;
height: 4em;
border-radius: 4em;
display: inline-flex;
justify-content: center;
align-items: center;
}
.UserIcon-letter {
font: 700 2em/0 sans-serif;
color: #fff;
}
_x000D_