JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

JavaScript

/**
 * RGB VALUES TO HEX COLOUR CODE
 * Set values as separate function parameter
 */
function rgb2hex(){
    // Open hex string
    var retval = '#';
    // Loop args up to 3 (R, G and B)
    for(var i = 0; i < arguments.length && i < 3; i++){
        // Type validation
        if(typeof arguments[i] !== 'number'){ return false; }
        // Double form creation for single digit hex numbers
        if(arguments[i] < 16){ retval += 0; }
        // Append converted base
        retval += arguments[i].toString(16);
    }
    return retval;
}

console.log(rgb2hex(255, 255, 255));
console.log(rgb2hex(230, 127, 94));
console.log(rgb2hex(0, 0, 0));

/**
 * HEX COLOUR CODE TO RGB ARRAY
 * h = hex code
 */
function hex2rgb(h){
    var ret = [],
        form = 2;
    // Pattern matching
    if(!h.match(/^#?[a-fA-F0-9]{3,6}$/ig)){
        return false;
    }
    h = h.replace(/[^a-fA-F0-9]+/ig, '');
    // Validate short form
    if(h.length == 6){
        form = 2; // Full 6 char form
    }else if(h.length == 3){
        form = 1; // Short 3 char form
    }else{
        return false; // Not a valid form
    }
    // Loop string on form base
    for(var i = 0; i < h.length; i += form){
        // Form double string build
        var d;
        if(form == 2){
            d = h[i] + '' + h[i+1];
        }else{   
            d = h[i] + '' + h[i];
        }
        // Set converted number in array
        ret[i/form] = parseInt(d, 16);
    }
    return ret;
}

console.log(hex2rgb('#fff'));
console.log(hex2rgb('#e67f5e'));
console.log(hex2rgb('#000000'));