×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Devin Gaul
Added: Jan 26, 2022 12:58 AM
Views: 392
Tags: convert hex rgb
  1. /**
  2.  * rgb2hex()
  3.  * Convert rgb to hexadecimal
  4.  *
  5.  * console.log(rgb2hex(255, 255, 255) === '#ffffff')
  6.  * console.log(rgb2hex(255, 99, 71) === '#ff6347')
  7.  */
  8. function rgb2hex(r, g, b) {
  9.   if (
  10.     typeof r !== 'number' ||
  11.     typeof g !== 'number' ||
  12.     typeof b !== 'number'
  13.   ) {
  14.     throw new TypeError('argument is not a Number')
  15.   }
  16.  
  17.   const toHex = n => (n || '0').toString(16).padStart(2, '0')
  18.  
  19.   return `#${toHex(r)}${toHex(g)}${toHex(b)}`
  20. }