get random hex color in typescript

Here's a function in TypeScript that generates a random hex color:

index.ts
function getRandomHexColor(): string {
  // Generate a random 6-digit hexadecimal number
  const randomColor = Math.floor(Math.random() * 16777215).toString(16);

  // Pad the number with leading zeros up to 6 digits
  return "#" + "0".repeat(6 - randomColor.length) + randomColor;
}
284 chars
8 lines

Explanation:

  1. Math.random() generates a random number between 0 and 1.
  2. Math.floor() rounds down that number to the nearest integer.
  3. 16777215 is 0xFFFFFF in decimal, which is the highest possible value for a 24-bit RGB color code.
  4. .toString(16) converts the random number to a hexadecimal string.
  5. We pad the string with leading zeros up to 6 digits, and prepend a '#' to get a valid hex color code.

You can use this function in your TypeScript code like this:

index.ts
const randomColor = getRandomHexColor();
console.log(randomColor); // e.g. "#8e14da"
85 chars
3 lines

gistlibby LogSnag