DEV Community

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

Collapse
 
awwsmm profile image
Andrew (he/him) • Edited

Scala, providing the shortest and most elegant solution so far ๐Ÿ˜Ž

def rgb(r: Int, g: Int, b: Int) = {
  def h(x: Int) = f"${x max 0 min 255}%02X"
  h(r) + h(g) + h(b)
}
Enter fullscreen mode Exit fullscreen mode

Tests

scala> rgb(255, 255, 255)
res24: String = FFFFFF

scala> rgb(255, 255, 300)
res25: String = FFFFFF

scala> rgb(0, 0, 0)
res26: String = 000000

scala> rgb(148, 0, 211)
res27: String = 9400D3

scala> rgb(-20, 275, 125)
res28: String = 00FF7D

scala> rgb(255, 255, 255)
res29: String = FFFFFF
Enter fullscreen mode Exit fullscreen mode