DEV Community

Discussion on: Daily Challenge #236 - RGB to Hex Conversion

Collapse
 
jpantunes profile image
JP Antunes • Edited

Here's a quick one-liner JS solution... It would look better with a helper function to validate min/max though :-)

const rgb = (r, g, b) => Buffer.from([Math.max(0, Math.min(255, r)), Math.max(0, Math.min(255, g)), Math.max(0, Math.min(255, b))]).toString('hex').toUpperCase()

edit:
Ok, so I came up with a nicer one-liner :-) but it requires using the funky Uint8ClampedArray, which normally shouldn't be used outside of canvas API... because it rounds values to nearest from 0 to 255... which is what we want! Without further ado:

const newRGB = (r, g, b) => Buffer.from(new Uint8ClampedArray([r, g, b])).toString('hex').toUpperCase()