Skip to content

Instantly share code, notes, and snippets.

@zmnv
Created October 28, 2019 16:40
Show Gist options
  • Save zmnv/1c612e8a47ead14fc6caf0355a9f319a to your computer and use it in GitHub Desktop.
Save zmnv/1c612e8a47ead14fc6caf0355a9f319a to your computer and use it in GitHub Desktop.
Continuous RGBA to HEXA converter
const readline = require('readline');
function colorToHex(rgb) {
let hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = `0${hex}`;
}
return hex;
};
function alphaToHex(alpha) {
const preHex = Math.round(alpha * 255);
const hex = (preHex + 0x10000).toString(16).substr(-2).toUpperCase();
return hex;
}
function rgbaToHex(r, g, b, a) {
const red = colorToHex(r);
const green = colorToHex(g);
const blue = colorToHex(b);
if (a === '1' || a === '0') {
return red + green + blue;
}
const alpha = alphaToHex(a);
return red + green + blue + alpha;
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askToConvert() {
rl.question('RGBA: ', (answer) => {
if (answer === 'exit') rl.close();
const withoutSpaces = answer.replace(/\s/g, '').replace(/rgba\(/g, '').replace(/\)/g, '');
const prepared = withoutSpaces.split(',');
const [r, g, b, a] = prepared;
const hex = rgbaToHex(r, g, b, a);
console.log(`#${hex}`);
askToConvert();
});
}
askToConvert();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment