Format RGB channels as hex
Colour pickers and interpolation code work in numbers, but CSS and <input type="color"> want #rrggbb. This conversion is where off-by-one padding bugs live: channel 1 must render as 01, not 1.
Implement rgbToHex(r, g, b). Each channel is first rounded with Math.round, then clamped into the range 0 to 255, then rendered as exactly two lowercase hex digits, zero-padded on the left.
Return the three channels concatenated after a single #, so the result is always exactly seven characters, lowercase — for example "#ff8800".
Arguments
rnumber- Red channel. Rounded and clamped into 0..255.
gnumber- Green channel. Rounded and clamped into 0..255.
bnumber- Blue channel. Rounded and clamped into 0..255.
Returns
string — A seven-character lowercase hex colour string in the form #rrggbb.
Examples
rgbToHex(255, 136, 0);
// => "#ff8800"A normal in-range colour renders as six lowercase digits after #.
rgbToHex(1, 2, 3);
// => "#010203"Single-digit channels are zero-padded to two digits each.
rgbToHex(300, -20, 12.6);
// => "#ff000d"Fractions are rounded, and out-of-range values are clamped into 0..255.
What it has to do
- Return a seven character string starting with
#, using lowercase hex digits. - Zero-pad each channel to two digits.
- Round fractional channel values with
Math.round. - Clamp values below 0 to 0 and above 255 to 255.
Notes
Math.rounduses banker's-free half-up rounding, so0.5becomes1. If a caller cares about half-even rounding they must round the channels themselves before calling.- Lowercase matches what
<input type="color">emits via its.valueproperty, so round-trips through the DOM compare with===.
Stuck? The javascript course covers everything this challenge needs.
- 1.formats a normal colour
- 2.zero pads single digit channels
- 3.handles pure black and pure white
- 4.clamps out of range values and rounds fractions
- 5.rounds half values up
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.