見習村19 - RGB To Hex Conversion

19 - RGB To Hex Conversion

Don’t say so much, just coding…

Instruction

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:

1
2
3
4
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3

Ruby

Init

1
2
3
def rgb(r, g, b)
# complete this function
end

Sample Testing

1
2
3
4
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')

Javascript

Init

1
2
3
function rgb(r, g, b){
// complete this function
}

Sample Testing

1
2
3
4
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')

Thinking

想法(1): 不管傳進來的值 (r, g, b) 都先考慮當數字不在 0 ~ 255 時,需要給最大、小值
想法(2): 判斷完成後,再轉為 16 進位

https://ithelp.ithome.com.tw/upload/images/20201004/20120826ebtZaU8Oav.jpg
圖片來源:Unsplash Jonathan Kemper

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
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()
}