This is a real quick one!
If you have a project that involves users interacting with each other, like a chat app or something with profiles, it might be nice to assign them a colour. A bit like WhatsApp names. The challenge is how to make sure the same users always have the same colour as themselves, but within a wide range such that it's effectively random?
You can use ASCII key codes and the modulo operator and combine with HSL for a quick solution that will always return a random, but identical, hue, thereby converting any string into colour.
const name = 'Michael Jordan';
const characters = name.split('');
const code = characters.map(a => a.charCodeAt(0)).join('');
// code is 771059910497101108327411111410097110
const hue = code % 255;
const nameHSL = `hsl(${hue}, 80%, 40%)`;
Of course, you might prefer to use a UID or 'user created at' timestamp in case you have two Michael Jordans - this works for literally any string!
For anyone wondering, MJ is this leafy green.
Lovely.
Top comments (5)
Very interesting, I've made a quick fiddle of it 😅
I love this!
I loved the blog and great work on the Fiddle man!
Interesting, both my name (kyle) and alias (seiyria) are the same color (#1458b8) - the green is off by a little bit but they're still really close!
!!
It would be interesting to crunch lots of names / random strings and see if this actually is nicely random, or it skews to certain colours. Instinctively I wonder if 255 is too round a number and if a prime might be better, but I'm not smart enough to work that one out.