Convert Hex Colours to RGB and Back
Write the code, see it run, pass the checks.
The problem
- easy
- Code
Write two functions. hexToRgb(hex) takes a colour written as "#" and six hex digits, such as "#ff8000", or the shorthand "#" and three digits, where each digit is doubled, so "#f80" is "#ff8800". Letters may be upper or lower case. It returns an object { r, g, b } of numbers from 0 to 255, or null for anything else: no "#", any other number of digits, or a character that isn't a hex digit. rgbToHex({ r, g, b }) does the reverse: it rounds each value to the nearest whole number, clamps it to 0 to 255, and returns "#" and six lowercase hex digits, two per channel, such as "#010203".
Your code must pass
- Parses six-digit hex colours
- Expands three-digit shorthand
- Returns null for anything that isn't a hex colour
- Formats RGB as six lowercase hex digits
- Rounds and clamps values when formatting