All files / src/functions colours.ts

100% Statements 22/22
100% Branches 0/0
100% Functions 9/9
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52        162x           46x       6x       3x 3x 3x 3x 3x       4x 4x 4x 4x 4x 4x       20x 60x 20x       2x 6x 2x                
import { clamp } from '@/functions/clamp';
import { ColourData } from '@3cr/types-ts/types/ColourData';
 
function toHex(n: number): string {
  return Math.floor(clamp(n, 0, 255))
    .toString(16)
    .padStart(2, '0');
}
 
export function rgbToHex(r: number, g: number, b: number): string {
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
 
export function rgbaToHex(r: number, g: number, b: number, a: number): string {
  return `#${toHex(r)}${toHex(g)}${toHex(b)}${toHex(a)}`;
}
 
export function hexToRgb(hex: string): [number, number, number] {
  const digits = hex.replace('#', '');
  const red = parseInt(digits.substring(0, 2), 16);
  const green = parseInt(digits.substring(2, 4), 16);
  const blue = parseInt(digits.substring(4, 6), 16);
  return [red, green, blue];
}
 
export function hexToRgba(hex: string): [number, number, number, number] {
  const digits = hex.replace('#', '');
  const red = parseInt(digits.substring(0, 2), 16);
  const green = parseInt(digits.substring(2, 4), 16);
  const blue = parseInt(digits.substring(4, 6), 16);
  const alpha = parseInt(digits.substring(6, 8), 16);
  return [red, green, blue, alpha];
}
 
export function fromColourData(value: ColourData): string {
  const { R, G, B } = value;
  const toByte = (x: number) => Math.floor(x * 255);
  return rgbToHex(toByte(R), toByte(G), toByte(B));
}
 
export function toColourData(value: string): ColourData {
  const [r, g, b] = hexToRgb(value);
  const toFloat = (x: number) => x / 255;
  return {
    Version: '0.0.0',
    R: toFloat(r),
    G: toFloat(g),
    B: toFloat(b),
    A: 1,
  };
}