how to change string "#FF0000" to complementary color value in typescript
- User
how to change string "#FF0000" to complementary color value in typescript
Assistant
Okay, to change a hex color string like "#FF0000" (Red) to its complementary color (which would be Cyan, "#00FFFF"), you need to:
- Parse the Hex String: Extract the Red, Green, and Blue (RGB) components.
- Convert to Decimal: Convert each hex component (00-FF) to its decimal equivalent (0-255).
- Calculate Complementary Values: For each component, subtract its value from 255.
R_complement = 255 - RG_complement = 255 - GB_complement = 255 - B
- Convert Back to Hex: Convert the new decimal complementary values back to 2-digit hex strings.
- Combine: Concatenate the new hex components with a "#" prefix.
Here's a TypeScript function to do this:
/** * Converts a hex color string to its complementary color. * @param hexColor The input hex color string (e.g., "#FF0000" or "FF0000"). * @returns The complementary hex color string (e.g., "#00FFFF"). * @throws Error if the hex color format is invalid. */ function getComplementaryColor(hexColor: string): string { // 1. Normalize and Validate Hex String let hex = hexColor.startsWith('#') ? hexColor.slice(1) : hexColor; if (hex.length === 3) { // Handle shorthand hex (e.g., "F00" -> "FF0000") hex = hex.split('').map(char => char + char).join(''); } if (hex.length !== 6 || !/^[0-9a-fA-F]{6}$/.test(hex)) { throw new Error(`Invalid hex color format: ${hexColor}. Expected #RRGGBB, RRGGBB, #RGB, or RGB.`); } // 2. Parse Hex to Decimal const r = parseInt(hex.substring(0, 2), 16); const g = parseInt(hex.substring(2, 4), 16); const b = parseInt(hex.substring(4, 6), 16); // 3. Calculate Complementary Values const rComp = 255 - r; const gComp = 255 - g; const bComp = 255 - b; // 4. Convert Complementary Decimal to Hex (and ensure 2 digits) const toHex = (c: number): string => { const hexVal = c.toString(16); return hexVal.length === 1 ? "0" + hexVal : hexVal; }; const rCompHex = toHex(rComp); const gCompHex = toHex(gComp); const bCompHex = toHex(bComp); // 5. Combine return `#${rCompHex}${gCompHex}${bCompHex}`.toUpperCase(); } // --- Examples --- try { const red = "#FF0000"; const complementaryRed = getComplementaryColor(red); console.log(`Original: ${red}, Complementary: ${complementaryRed}`); // Expected: #00FFFF (Cyan) const green = "00FF00"; // Without '#' const complementaryGreen = getComplementaryColor(green); console.log(`Original: #${green}, Complementary: ${complementaryGreen}`); // Expected: #FF00FF (Magenta) const blue = "#00F"; // Shorthand Blue (#0000FF) const complementaryBlue = getComplementaryColor(blue); console.log(`Original: ${blue} (#0000FF), Complementary: ${complementaryBlue}`); // Expected: #FFFF00 (Yellow) const yellow = "#FFFF00"; const complementaryYellow = getComplementaryColor(yellow); console.log(`Original: ${yellow}, Complementary: ${complementaryYellow}`); // Expected: #0000FF (Blue) const customColor = "#34A853"; // A shade of green const complementaryCustom = getComplementaryColor(customColor); console.log(`Original: ${customColor}, Complementary: ${complementaryCustom}`); // Expected: #CB57AC const grey = "#808080"; const complementaryGrey = getComplementaryColor(grey); console.log(`Original: ${grey}, Complementary: ${complementaryGrey}`); // Expected: #7F7F7F (A slightly different grey) // Example of invalid input // const invalidColor = "#12345"; // console.log(getComplementaryColor(invalidColor)); } catch (error) { if (error instanceof Error) { console.error(error.message); } else { console.error("An unknown error occurred:", error); } }Explanation:
getComplementaryColor(hexColor: string): string: Defines the function that takes a hex string and returns a hex string.- Normalize and Validate:
- It first removes the leading
#if present. - It then checks if the input is a shorthand hex (e.g.,
#RGB). If so, it expands it to the full 6-digit form (e.g.,#RRGGBB). - It validates if the resulting hex string is exactly 6 characters long and consists only of valid hexadecimal characters (0-9, a-f, A-F). If not, it throws an error.
- It first removes the leading
- Parse Hex to Decimal:
hex.substring(0, 2)gets the "RR" part.parseInt(..., 16)converts the hex substring to its decimal (base 10) equivalent.
- Calculate Complementary Values: Simple subtraction from 255.
- Convert Complementary Decimal to Hex:
- The
toHexhelper function converts a decimal number (0-255) to its 2-digit hexadecimal string representation. c.toString(16)converts the number to a hex string.hexVal.length === 1 ? "0" + hexVal : hexVal;ensures that if the hex value is a single digit (e.g., "F" for 15), it's prepended with a "0" to become "0F".
- The
- Combine: The new hex components are joined together with a
#at the beginning, and.toUpperCase()ensures the hex letters are uppercase for consistency.
This function is robust enough to handle hex codes with or without the
#prefix and also supports 3-digit shorthand hex codes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.