Created
          March 12, 2023 06:55 
        
      - 
      
 - 
        
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
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Example:
Color.asName({ r: 243, g: 0, b: 0 }); // "red"