Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a series of unique HEX colors in TypeScript

1 Answer

0 votes
/**
 * Generate N unique random HEX colors (#RRGGBB).
 * @param count Number of unique colors to generate.
 * @returns Array of HEX color strings.
 */
export function generateRandomUniqueHexColors(count: number): string[] {
  // A Set ensures uniqueness automatically
  const colors: Set<string> = new Set();

  while (colors.size < count) {
    // Create 3 random bytes (R, G, B)
    const bytes: Uint8Array = new Uint8Array(3);
    crypto.getRandomValues(bytes); // secure random values

    // Convert bytes → hex string (#RRGGBB)
    const hex: string =
      `#${Array.from(bytes)
        .map((v: number) => v.toString(16).padStart(2, "0"))
        .join("")}`;

    colors.add(hex); // Set ignores duplicates
  }

  // Convert Set → Array
  const result: string[] = Array.from(colors);

  return result;
}

// Example usage
const colors: string[] = generateRandomUniqueHexColors(12);

console.log("Generated HEX colors:");
colors.forEach((c: string) => console.log(c));



/*
run:

Generated HEX colors:
#e3c828
#45f4e5
#6c1de0
#2676d8
#516505
#04ebe7
#9fa377
#b867c5
#61e26e
#f65fa9
#b53342
#2ddc10

*/

 



answered 13 hours ago by avibootz
...