color-utilities-in-javascript

star 49

Explore helpful color utility functions, like RGB to HSL, HEX to RGB, and HSL to HEX, generated with the assistance of GitHub Copilot.

rodydavis By rodydavis schedule Updated 2/3/2026

name: color-utilities-in-javascript description: Explore helpful color utility functions, like RGB to HSL, HEX to RGB, and HSL to HEX, generated with the assistance of GitHub Copilot. metadata: url: https://rodydavis.com/posts/snippets/typescript-color-utilities last_modified: Tue, 03 Feb 2026 20:04:31 GMT

Color Utilities in JavaScript

Color utilities generated by GitHub Copilot.

Convert an RGB color to HSL

function rgbToHsl(r, g, b) {
    r /= 255;
    g /= 255;
    b /= 255;
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;
    if (max == min) {
        h = s = 0;
    } else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch (max) {
            case r:
                h = (g - b) / d + (g < b ? 6 : 0);
                break;
            case g:
                h = (b - r) / d + 2;
                break;
            case b:
                h = (r - g) / d + 4;
                break;
        }
        h /= 6;
    }
    return [h, s, l];
} 

Convert HEX to RGB

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

Convert HSL to HEX

function hslToHex(h, s, l) {
    var r, g, b;
    if (s == 0) {
        r = g = b = l;
    } else {
        var hue2rgb = function hue2rgb(p, q, t) {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1 / 6) return p + (q - p) * 6 * t;
            if (t < 1 / 2) return q;
            if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
            return p;
        };
        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1 / 3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1 / 3);
    }
    return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}
Install via CLI
npx skills add https://github.com/rodydavis/skills --skill color-utilities-in-javascript
Repository Details
star Stars 49
call_split Forks 5
navigation Branch main
article Path SKILL.md
More from Creator