/**
* Generate a random RGBA color in TypeScript.
*
* Notes:
* - Uses Math.random() for uniform random values.
* - Produces integer RGB values in [0, 255].
* - Produces opacity (alpha) in [0, 1] with full floating‑point precision.
* - Returns a formatted CSS RGBA string: "rgba(r, g, b, a)".
*/
/** A strongly typed structure representing an RGBA color. */
type RGBA = {
r: number; // red component (0–255)
g: number; // green component (0–255)
b: number; // blue component (0–255)
a: number; // alpha component (0–1)
};
/** Generate a random integer in the range [0, 255]. */
function randomChannel(): number {
return Math.floor(Math.random() * 256);
}
/** Generate a random opacity value in the range [0, 1]. */
function randomOpacity(): number {
return Math.random();
}
/** Create a random RGBA color object. */
function generateRandomRGBA(): RGBA {
return {
r: randomChannel(),
g: randomChannel(),
b: randomChannel(),
a: randomOpacity()
};
}
/** Convert an RGBA object into a CSS rgba(...) string. */
function rgbaToCss(color: RGBA): string {
const { r, g, b, a } = color;
return `rgba(${r}, ${g}, ${b}, ${a.toFixed(3)})`;
// toFixed(3) keeps opacity readable while still precise
}
/** Example usage */
const color: RGBA = generateRandomRGBA();
const cssString: string = rgbaToCss(color);
console.log("Generated RGBA color object:", color);
console.log("CSS RGBA string:", cssString);
/*
run:
Generated RGBA color object: { r: 36, g: 157, b: 91, a: 0.4803201838549229 }
CSS RGBA string: rgba(36, 157, 91, 0.480)
*/