# codewars--js--RGB To Hex Conversion

2018/04/19 10:04

The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should 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

function rgb(r, g, b){
// complete this function
r=a(r);g=a(g);b=a(b);
r=r.toString(16).toUpperCase();
g=g.toString(16).toUpperCase();
b=b.toString(16).toUpperCase();
var c=r.concat(g).concat(b);
if(c=="000"){return "000000";}
else{return c;}
}
function a(n){
if(n>255){return n=255;}
if(n<0){return n=0;}
if(n>=0 && n<=255){return n;}
}

（1）

function rgb(r, g, b){
}

function toHex(d) {
if(d < 0 ) {return "00";}
if(d > 255 ) {return "FF";}
return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()  //slice（-2）作用若为0，则返回00；若为255，则返回ff
}

（2）

function rgb(r, g, b){
return [r,g,b].map(function(x) {
return ('0'+Math.max(0, Math.min(255, x)).toString(16)).slice(-2);  //将<0或>255的分别置为0或255.
}).join('').toUpperCase();
}

0
0 收藏

0 评论
0 收藏
0