-1

I saw this gist to change RGB color to RGBA, but JS Math does not have a range method. Is there any way to convert the range method here?

function rgba(hex, opacity) {
    var colours = hex.regex(/#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})/i).map(function(val) {
        return Math.range(0, parseInt(val, 16), 255);
    }).join(",");
    if (opacity === undefined) {
        return "rgb(" + colours + ")";
    }
    return "rgba(" + colours + "," + opacity + ")";
}

Found this here: https://gist.github.com/Rycochet/8597336

pertrai1
  • 4,146
  • 11
  • 46
  • 71

2 Answers2

2

It appears to me that range method just clamps the value. You can do that by combining max and min methods.

Math.range = function(min, val, max) {
  return Math.max(min, Math.min(val, max));
};
kamoroso94
  • 1,713
  • 1
  • 16
  • 19
  • Or `var clamp = (min, val, max) => val < min ? min : val > max ? max : val`. `range` is an odd name for this function. I've usually seen `range(3, 6) //=> [3, 4, 5, 6]` or some variant of it.. – Scott Sauyet Jan 24 '18 at 15:15
1

To fulfill the color conversion without range

function rgba(hex, opacity) {
    var colours = hexToRgb(hex);
    if (opacity === undefined) {
        return "rgb(" + colours + ")";
    }
    return "rgba(" + colours + "," + opacity + ")";
}

function hexToRgb(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}

The function hexToRgb(hex) was from RGB to Hex and Hex to RGB

ild flue
  • 1,323
  • 8
  • 9
  • thank you for the response. In regards to the way that `Math.range` is being used in this case, how would I convert that to not be using `range` – pertrai1 Jan 24 '18 at 14:50
  • I updated it with a code to fulfill the color conversion without `range` – ild flue Jan 24 '18 at 15:00