Skip to content

Instantly share code, notes, and snippets.

@LiamPerson
Created March 12, 2023 06:55
Show Gist options
  • Save LiamPerson/54d05ec602684de9daba74a821155af9 to your computer and use it in GitHub Desktop.
Save LiamPerson/54d05ec602684de9daba74a821155af9 to your computer and use it in GitHub Desktop.
Color name inference class made for Typescript. Converts any {r: number, g: number, b: number} to a name defined by BASE_COLORS
export type RGBColor = {
r: number;
g: number;
b: number;
}
class Color {
/**
* Available color names to be used in the `asName` method
*/
static BASE_COLORS = {
black: [0, 0, 0],
white: [255, 255, 255],
red: [255, 0, 0],
green: [0, 128, 0],
blue: [0, 0, 255],
yellow: [255, 255, 0],
cyan: [0, 255, 255],
magenta: [255, 0, 255],
};
/**
* Converts a color object to a name as defined by the `BASE_COLORS` object
* @param color
* @returns
*/
static asName = (color: RGBColor): string => {
// Calculate the Euclidean distance between the input color and each basic color
let minDistance = Infinity;
let nearestColor = "";
for (const [name, basicRgb] of Object.entries(Color.BASE_COLORS)) {
const distance = Math.sqrt(
Object.values(basicRgb).reduce(
(sum, value, i) =>
sum +
Math.pow(value - color[Object.keys(color)[i] as keyof RGBColor], 2),
0
)
);
if (distance < minDistance) {
minDistance = distance;
nearestColor = name;
}
}
return nearestColor;
};
}
export default Color;
@LiamPerson
Copy link
Author

Example:
Color.asName({ r: 243, g: 0, b: 0 }); // "red"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment