Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active November 14, 2018 09:57
Show Gist options
  • Save gladchinda/22d03e5dd656d5df07922b9b3852da16 to your computer and use it in GitHub Desktop.
Save gladchinda/22d03e5dd656d5df07922b9b3852da16 to your computer and use it in GitHub Desktop.
function leftZeroPad(value, maxlength) {
while (value.length < maxlength) {
value = '0' + value;
}
return value;
}
function boundedValue(minvalue, maxvalue) {
return function(value) {
return Math.max(minvalue, Math.min(maxvalue, +value || 0));
}
}
function colorValue(value) {
var hex = boundedValue(0, 255)(value).toString(16);
return leftZeroPad(hex, 2);
}
function rgbToHex(red, green, blue) {
red = colorValue(red);
green = colorValue(green);
blue = colorValue(blue);
return '#' + red + green + blue;
}
console.log(rgbToHex()); // "#000000"
console.log(rgbToHex(255)); // "#ff0000"
console.log(rgbToHex(255, 128)); // "#ff8000"
console.log(rgbToHex(255, 128, 64)); // "#ff8040"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment