Don't say so much, just coding...
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
def rgb(r, g, b)
# complete this function
end
Test.assert_equals(rgb(0, 0, 0), '000000')
Test.assert_equals(rgb(0, 0, -20), '000000')
Test.assert_equals(rgb(300,255,255), 'FFFFFF')
Test.assert_equals(rgb(173,255,47), 'ADFF2F')
function rgb(r, g, b){
// complete this function
}
Test.assertEquals(rgb(0, 0, 0), '000000')
Test.assertEquals(rgb(0, 0, -20), '000000')
Test.assertEquals(rgb(300,255,255), 'FFFFFF')
Test.assertEquals(rgb(173,255,47), 'ADFF2F')
想法(1): 不管傳進來的值 (r, g, b)
都先考慮當數字不在 0 ~ 255
時,需要給最大、小值
想法(2): 判斷完成後,再轉為 16
進位
# Solution 1
def rgb(r, g, b)
[r, g, b].map do |c|
if c <= 0
"00"
elsif c > 255
"FF"
else
c.to_s(16).upcase
end
end.join('')
end
# Solution 2
def rgb(r, g, b)
"%.2X" * 3 % [r, g, b].map{ |i| [[i, 255].min, 0].max }
end
# Solution 3
def rgb(r, g, b)
"%.2X" * 3 % [r, g, b].map{ |i| i.clamp(0, 255) }
end
// Solution 1
function rgb(r, g, b){
return toHex(r) + toHex(g) + toHex(b);
}
function toHex(color) {
if(color < 0)
return "00";
if(color > 255)
return "FF";
return ( "0" + (Number(color).toString(16)) )
.slice(-2)
.toUpperCase()
}