DEV Community

Discussion on: Different possible methods for generating a colour randomly in JS

Collapse
 
rpm profile image
Ryan McCormick • Edited

Not a random color exactly, but here is code I wrote that produces a nice pastel color from any string, and will always be the same for that same string (it actually only uses the first 2 and last letters of the string).

  //--- START Helper Functions ------------------------------------------------\\
  function Colorize(seed = 'AA')
   {//Returns a pastel color based on 1st, 2nd, and Last characters in a string.
    if (seed.length = 0) {seed = 'AA';} else
    if (seed.length = 1) {seed += 'A';}
    r = (seed.charCodeAt(0) * 9).toString(16).slice(-2);
    g = (seed.charCodeAt(1) * 9).toString(16).slice(-2);
    b = (seed.charCodeAt(seed.length-1) * 9).toString(16).slice(-2);
    return '#'+r+g+b;
   }
  //----------------------------------------------------------------------------
Enter fullscreen mode Exit fullscreen mode

I use it to color-code categories, even when the user can enter their own categories.

Collapse
 
loucyx profile image
Lou Cyx

There are a few typos in your function. The ifs are not comparing, they are assigning to seed.length. Also r, g and b are being defined globally. Here is the fix:

function Colorize(seed = "AA") {
    if (seed.length === 0) {
        seed = "AA";
    } else if (seed.length === 1) {
        seed += "A";
    }
    const r = (seed.charCodeAt(0) * 9).toString(16).slice(-2);
    const g = (seed.charCodeAt(1) * 9).toString(16).slice(-2);
    const b = (seed.charCodeAt(seed.length - 1) * 9).toString(16).slice(-2);
    return "#" + r + g + b;
}
Enter fullscreen mode Exit fullscreen mode

And if you want to take it one step further:

const stringToColor = (seed = "") =>
    (paddedSeed =>
        `#${[
            paddedSeed.charCodeAt(0),
            paddedSeed.charCodeAt(Math.floor(paddedSeed.length / 2)),
            paddedSeed.charCodeAt(paddedSeed.length - 1),
        ]
            .map(value => (value * 9).toString(16).slice(-2))
            .join("")}`)(seed.padEnd(3, "A"));

Enter fullscreen mode Exit fullscreen mode

Cheers!