// Convert number to hex string.pubfnto_hex(value:i32)->String{letvalue=ifvalue>255{255}elseifvalue<0{0}else{value};format!("{:02X}",value)}// Join all hex strings together from rgb input.pubfnrgb(r:i32,g:i32,b:i32)->String{format!("{}{}{}",to_hex(r),to_hex(g),to_hex(b))}#[cfg(test)]modtests{usesuper::*;#[test]fnit_should_be_black(){assert_eq!(rgb(255,255,255),"FFFFFF".to_string());}#[test]fnit_should_be_black_too(){assert_eq!(rgb(255,255,300),"FFFFFF".to_string());}#[test]fnit_should_be_white(){assert_eq!(rgb(0,0,0),"000000".to_string());}#[test]fnit_should_be_other(){assert_eq!(rgb(148,0,211),"9400D3".to_string());}}
Full-time web dev; JS lover since 2002; CSS fanatic. #CSSIsAwesome
I try to stay up with new web platform features. Web feature you don't understand? Tell me! I'll write an article!
He/him
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:
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:
In javascript
Haskell solution:
Python
You need to create a
rgbfunction which takes three arguments. Also, this challenge didn't specify to put#at the start.BeanShell
Run this code using AJShA Android app
Here's my solution, with C
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:
Here is the simple PHP solution: