Description

The 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.

Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.

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

Solutions

Julia


function convert2hex(x::Int64)::String
    string(clamp(x, 0, 255); base=16, pad=2)
end
#> convert2hex (generic function with 1 method)
convert2hex(12)
#> "0c"


function rgb(r::Int64, g::Int64, b::Int64)::String
    [r, g, b] .|> convert2hex |> join |> uppercase
    # string(convert2hex.([r, g, b])...) |> uppercase
end
#> rgb (generic function with 1 method)
rgb(-20, 275, 125)
#> "00FF7D"

R

## RGB To Hex Conversion

library(tidyverse)


#' @description Convert a number from decimal to hex.
#'   Any values out of [0, 255] must be rounded to the range
#' @param x 10 进制 integer
#' @return 补齐至两位的字符串,表示16进制的数字
convert2hex <- function(x) {
  max(0, min(x, 255)) %>% # round to [0, 255]
    as.hexmode() %>% # convert to 16 进制
    toupper() %>%
    str_pad(2, "left", "0")
}

rgb <- function(r, g, b) {
  c(r, g, b) %>%
    map_chr(convert2hex) %>%
    str_c(collapse = "")
}


library(testthat)
test_that("Example Tests", {
  expect_equal(rgb(0, 0, 0), "000000")
  expect_equal(rgb(1, 2, 3), "010203")
  expect_equal(rgb(255, 255, 255), "FFFFFF")
  expect_equal(rgb(254, 253, 252), "FEFDFC")
  expect_equal(rgb(-20, 275, 125), "00FF7D")
})
#> Test passed 😸

JavaScript


convert2hex = integer =>
  Math.max(0, Math.min(255, integer)).toString(16).padStart(2, "0");

function rgb(r, g, b) {
  return [r, g, b].map(convert2hex).join("").toUpperCase();
}

console.log(rgb(-20, 275, 125));
#> 00FF7D