This rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
The following are examples of expected output values:
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
Tests:
rgb(-20,275,125)
rgb(255,255,255)
This challenge comes from jhoffner on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (13)
Here is a short Python solution,
Output,
Scala, providing the shortest and most elegant solution so far 😎
Tests
In rust:
Rust Playground
GitHub Gist
A similar solution in R
Tests
JavaScript:
Haskell solution:
Python
You need to create a
rgb
function which takes three arguments. Also, this challenge didn't specify to put#
at the start.Here's a quick one-liner JS solution... It would look better with a helper function to validate min/max though :-)
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:
In javascript
Here is the simple PHP solution: