DEV Community

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

Collapse
 
kvharish profile image
K.V.Harish • Edited

In javascript

const toHex = (c) => {
const toHex = (c) => {
  const hex = Math.max(0, Math.min(255, c)).toString(16);
  return hex.length == 1 ? `0${hex}` : hex;
};

const rgb = (r, g, b) => {
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
};

rgb(255, 255, 255) // #ffffff
rgb(255, 255, 300) // #ffffff
rgb(0,0,0) // #000000
rgb(148, 0, 211) // #9400d3
rgb(-20,275,125) // #00ff7d
rgb(255,255,255) // #ffffff