Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

Refactoriza el siguiente código escrito en nim para que sea más eficiente y fácil de…

  1. User

    Refactoriza el siguiente código escrito en nim para que sea más eficiente y fácil de entender:

    import strutils, math, strformat
    
    #-- Convert hex color to RGB
    proc hexToRgb(hexColor: string): tuple[r, g, b: int] =
      var hexColor = hexColor.replace("#", "")
      result = (
        r: hexColor[0..1].parseHexInt,
        g: hexColor[2..3].parseHexInt,
        b: hexColor[4..5].parseHexInt
      )
    
    #-- Calculate the squared distance between two RGB colors
    proc distance(r1, g1, b1, r2, g2, b2: int): int =
      (r1 - r2)^2 + (g1 - g2)^2 + (b1 - b2)^2
    
    #-- Convert RGB to the closest ANSI 256 color
    proc rgbToAnsi(r, g, b: int): int =
      # ANSI color cube definition (6x6x6)
      let ansiColors = @[
        (0x00, 0x00, 0x00), (0x00, 0x00, 0x5f), (0x00, 0x00, 0x87), (0x00, 0x00, 0xaf), (0x00, 0x00, 0xd7), (0x00, 0x00, 0xff),
        (0x00, 0x5f, 0x00), (0x00, 0x5f, 0x5f), (0x00, 0x5f, 0x87), (0x00, 0x5f, 0xaf), (0x00, 0x5f, 0xd7), (0x00, 0x5f, 0xff),
        (0x00, 0x87, 0x00), (0x00, 0x87, 0x5f), (0x00, 0x87, 0x87), (0x00, 0x87, 0xaf), (0x00, 0x87, 0xd7), (0x00, 0x87, 0xff),
        (0x00, 0xaf, 0x00), (0x00, 0xaf, 0x5f), (0x00, 0xaf, 0x87), (0x00, 0xaf, 0xaf), (0x00, 0xaf, 0xd7), (0x00, 0xaf, 0xff),
        (0x00, 0xd7, 0x00), (0x00, 0xd7, 0x5f), (0x00, 0xd7, 0x87), (0x00, 0xd7, 0xaf), (0x00, 0xd7, 0xd7), (0x00, 0xd7, 0xff),
        (0x00, 0xff, 0x00), (0x00, 0xff, 0x5f), (0x00, 0xff, 0x87), (0x00, 0xff, 0xaf), (0x00, 0xff, 0xd7), (0x00, 0xff, 0xff),
        (0x5f, 0x00, 0x00), (0x5f, 0x00, 0x5f), (0x5f, 0x00, 0x87), (0x5f, 0x00, 0xaf), (0x5f, 0x00, 0xd7), (0x5f, 0x00, 0xff),
        (0x5f, 0x5f, 0x00), (0x5f, 0x5f, 0x5f), (0x5f, 0x5f, 0x87), (0x5f, 0x5f, 0xaf), (0x5f, 0x5f, 0xd7), (0x5f, 0x5f, 0xff),
        (0x5f, 0x87, 0x00), (0x5f, 0x87, 0x5f), (0x5f, 0x87, 0x87), (0x5f, 0x87, 0xaf), (0x5f, 0x87, 0xd7), (0x5f, 0x87, 0xff),
        (0x5f, 0xaf, 0x00), (0x5f, 0xaf, 0x5f), (0x5f, 0xaf, 0x87), (0x5f, 0xaf, 0xaf), (0x5f, 0xaf, 0xd7), (0x5f, 0xaf, 0xff),
        (0x5f, 0xd7, 0x00), (0x5f, 0xd7, 0x5f), (0x5f, 0xd7, 0x87), (0x5f, 0xd7, 0xaf), (0x5f, 0xd7, 0xd7), (0x5f, 0xd7, 0xff),
        (0x5f, 0xff, 0x00), (0x5f, 0xff, 0x5f), (0x5f, 0xff, 0x87), (0x5f, 0xff, 0xaf), (0x5f, 0xff, 0xd7), (0x5f, 0xff, 0xff),
        (0x87, 0x00, 0x00), (0x87, 0x00, 0x5f), (0x87, 0x00, 0x87), (0x87, 0x00, 0xaf), (0x87, 0x00, 0xd7), (0x87, 0x00, 0xff),
        (0x87, 0x5f, 0x00), (0x87, 0x5f, 0x5f), (0x87, 0x5f, 0x87), (0x87, 0x5f, 0xaf), (0x87, 0x5f, 0xd7), (0x87, 0x5f, 0xff),
        (0x87, 0x87, 0x00), (0x87, 0x87, 0x5f), (0x87, 0x87, 0x87), (0x87, 0x87, 0xaf), (0x87, 0x87, 0xd7), (0x87, 0x87, 0xff),
        (0x87, 0xaf, 0x00), (0x87, 0xaf, 0x5f), (0x87, 0xaf, 0x87), (0x87, 0xaf, 0xaf), (0x87, 0xaf, 0xd7), (0x87, 0xaf, 0xff),
        (0x87, 0xd7, 0x00), (0x87, 0xd7, 0x5f), (0x87, 0xd7, 0x87), (0x87, 0xd7, 0xaf), (0x87, 0xd7, 0xd7), (0x87, 0xd7, 0xff),
        (0x87, 0xff, 0x00), (0x87, 0xff, 0x5f), (0x87, 0xff, 0x87), (0x87, 0xff, 0xaf), (0x87, 0xff, 0xd7), (0x87, 0xff, 0xff),
        (0xaf, 0x00, 0x00), (0xaf, 0x00, 0x5f), (0xaf, 0x00, 0x87), (0xaf, 0x00, 0xaf), (0xaf, 0x00, 0xd7), (0xaf, 0x00, 0xff),
        (0xaf, 0x5f, 0x00), (0xaf, 0x5f, 0x5f), (0xaf, 0x5f, 0x87), (0xaf, 0x5f, 0xaf), (0xaf, 0x5f, 0xd7), (0xaf, 0x5f, 0xff),
        (0xaf, 0x87, 0x00), (0xaf, 0x87, 0x5f), (0xaf, 0x87, 0x87), (0xaf, 0x87, 0xaf), (0xaf, 0x87, 0xd7), (0xaf, 0x87, 0xff),
        (0xaf, 0xaf, 0x00), (0xaf, 0xaf, 0x5f), (0xaf, 0xaf, 0x87), (0xaf, 0xaf, 0xaf), (0xaf, 0xaf, 0xd7), (0xaf, 0xaf, 0xff),
        (0xaf, 0xd7, 0x00), (0xaf, 0xd7, 0x5f), (0xaf, 0xd7, 0x87), (0xaf, 0xd7, 0xaf), (0xaf, 0xd7, 0xd7), (0xaf, 0xd7, 0xff),
        (0xaf, 0xff, 0x00), (0xaf, 0xff, 0x5f), (0xaf, 0xff, 0x87), (0xaf, 0xff, 0xaf), (0xaf, 0xff, 0xd7), (0xaf, 0xff, 0xff),
        (0xd7, 0x00, 0x00), (0xd7, 0x00, 0x5f), (0xd7, 0x00, 0x87), (0xd7, 0x00, 0xaf), (0xd7, 0x00, 0xd7), (0xd7, 0x00, 0xff),
        (0xd7, 0x5f, 0x00), (0xd7, 0x5f, 0x5f), (0xd7, 0x5f, 0x87), (0xd7, 0x5f, 0xaf), (0xd7, 0x5f, 0xd7), (0xd7, 0x5f, 0xff),
        (0xd7, 0x87, 0x00), (0xd7, 0x87, 0x5f), (0xd7, 0x87, 0x87), (0xd7, 0x87, 0xaf), (0xd7, 0x87, 0xd7), (0xd7, 0x87, 0xff),
        (0xd7, 0xaf, 0x00), (0xd7, 0xaf, 0x5f), (0xd7, 0xaf, 0x87), (0xd7, 0xaf, 0xaf), (0xd7, 0xaf, 0xd7), (0xd7, 0xaf, 0xff),
        (0xd7, 0xd7, 0x00), (0xd7, 0xd7, 0x5f), (0xd7, 0xd7, 0x87), (0xd7, 0xd7, 0xaf), (0xd7, 0xd7, 0xd7), (0xd7, 0xd7, 0xff),
        (0xd7, 0xff, 0x00), (0xd7, 0xff, 0x5f), (0xd7, 0xff, 0x87), (0xd7, 0xff, 0xaf), (0xd7, 0xff, 0xd7), (0xd7, 0xff, 0xff),
        (0xff, 0x00, 0x00), (0xff, 0x00, 0x5f), (0xff, 0x00, 0x87), (0xff, 0x00, 0xaf), (0xff, 0x00, 0xd7), (0xff, 0x00, 0xff),
        (0xff, 0x5f, 0x00), (0xff, 0x5f, 0x5f), (0xff, 0x5f, 0x87), (0xff, 0x5f, 0xaf), (0xff, 0x5f, 0xd7), (0xff, 0x5f, 0xff),
        (0xff, 0x87, 0x00), (0xff, 0x87, 0x5f), (0xff, 0x87, 0x87), (0xff, 0x87, 0xaf), (0xff, 0x87, 0xd7), (0xff, 0x87, 0xff),
        (0xff, 0xaf, 0x00), (0xff, 0xaf, 0x5f), (0xff, 0xaf, 0x87), (0xff, 0xaf, 0xaf), (0xff, 0xaf, 0xd7), (0xff, 0xaf, 0xff),
        (0xff, 0xd7, 0x00), (0xff, 0xd7, 0x5f), (0xff, 0xd7, 0x87), (0xff, 0xd7, 0xaf), (0xff, 0xd7, 0xd7), (0xff, 0xd7, 0xff),
        (0xff, 0xff, 0x00), (0xff, 0xff, 0x5f), (0xff, 0xff, 0x87), (0xff, 0xff, 0xaf), (0xff, 0xff, 0xd7), (0xff, 0xff, 0xff),
        # Grayscale colors
        (0x08, 0x08, 0x08), (0x12, 0x12, 0x12), (0x1c, 0x1c, 0x1c), (0x26, 0x26, 0x26), (0x30, 0x30, 0x30), (0x3a, 0x3a, 0x3a),
        (0x44, 0x44, 0x44), (0x4e, 0x4e, 0x4e), (0x58, 0x58, 0x58), (0x62, 0x62, 0x62), (0x6c, 0x6c, 0x6c), (0x76, 0x76, 0x76),
        (0x80, 0x80, 0x80), (0x8a, 0x8a, 0x8a), (0x94, 0x94, 0x94), (0x9e, 0x9e, 0x9e), (0xa8, 0xa8, 0xa8), (0xb2, 0xb2, 0xb2),
        (0xbc, 0xbc, 0xbc), (0xc6, 0xc6, 0xc6), (0xd0, 0xd0, 0xd0), (0xda, 0xda, 0xda), (0xe4, 0xe4, 0xe4), (0xee, 0xee, 0xee)
      ]
    
      var bestMatch = 0
      var bestDistance = distance(r, g, b, ansiColors[0][0], ansiColors[0][1], ansiColors[0][2])
    
      for i in 1..<ansiColors.len:
        let dist = distance(r, g, b, ansiColors[i][0], ansiColors[i][1], ansiColors[i][2])
        if dist < bestDistance:
          bestMatch = i
          bestDistance = dist
    
      return bestMatch + 16 # ANSI colors start at 16
    
    #-- Convert hex color to ANSI color -------------------------------------------
    proc hexToAnsi(hex: string, mode: int): string =
      let (r, g, b) = hexToRgb(hex)
      let ansiCode = rgbToAnsi(r, g, b)
      result = (if mode != 1: &"\e[38;5;{ansiCode}m" else: &"\e[48;5;{ansiCode}m")
    
    #-- Foreground and background
    proc fg(hex: string): string = hexToAnsi(hex, 0)
    proc bg(hex: string): string = hexToAnsi(hex, 1)
    
    #-- Foreground and background in compTime
    proc fgx(hex: static string): string = static(hexToAnsi(hex, 0))
    proc bgx(hex: static string): string = static(hexToAnsi(hex, 1))
    
    # Example usage:
    # const hexColor = "#FFFF00"
    # const ansiColor = hexToAnsi(hexColor, 0)
    # echo ansiColor, "Hello world!"
    
    export hexToAnsi, fg, bg, fgx, bgx
    
  2. Assistant

    Claro, a continuación encontrarás una versión refactorizada del código en Nim que mejora la eficiencia y legibilidad. Las principales mejoras incluyen:

    1. Generación Programática de la Paleta ANSI: En lugar de listar manualmente todas las combinaciones de colores ANSI, la paleta se genera programáticamente, lo que reduce la redundancia y facilita futuras modificaciones.
    2. Definición Clara de Tipos: Se utiliza un tipo RGB para representar colores, lo que mejora la claridad del código.
    3. Validación de Entrada: Se añade validación en la función hexToRgb para asegurar que el color hexadecimal tenga el formato correcto.
    4. Optimización de Cálculos: Se simplifican las funciones de cálculo de distancia y conversión.

    Aquí está el código refactorizado:

    import strutils, math, strformat
    
    # Definir una tupla RGB para mayor claridad
    type
      RGB = tuple[r, g, b: int]
    
    # Niveles de color para el cubo 6x6x6
    const
      colorLevels = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
    
    # Generar el cubo de colores ANSI 6x6x6 (216 colores)
    let colorCube: seq[RGB] = @[]
    for r in colorLevels:
      for g in colorLevels:
        for b in colorLevels:
          colorCube.add(RGB(r: r, g: g, b: b))
    
    # Generar los 24 niveles de gris
    let grayscaleLevels: seq[RGB] = @[]
    for i in 0..<24:
      let level = 8 + i * 10
      grayscaleLevels.add(RGB(r: level, g: level, b: level))
    
    # Combinar el cubo de colores y los grises en una sola lista
    const ansiPalette = colorCube & grayscaleLevels
    
    #-- Convertir color hexadecimal a RGB
    proc hexToRgb(hexColor: string): RGB =
      let cleanedHex = hexColor.stripPrefix("#")
      if cleanedHex.len != 6:
        raise newException(ValueError, "Formato de color hexadecimal inválido")
      result.r = cleanedHex[0..1].parseHexInt
      result.g = cleanedHex[2..3].parseHexInt
      result.b = cleanedHex[4..5].parseHexInt
    
    #-- Calcular la distancia al cuadrado entre dos colores RGB
    proc squaredDistance(a, b: RGB): int =
      (a.r - b.r).pow(2) + (a.g - b.g).pow(2) + (a.b - b.b).pow(2)
    
    #-- Convertir RGB al color ANSI 256 más cercano
    proc rgbToAnsi(target: RGB): int =
      var bestMatch = 0
      var bestDistance = squaredDistance(target, ansiPalette[0])
    
      for i in 1..<ansiPalette.len:
        let dist = squaredDistance(target, ansiPalette[i])
        if dist < bestDistance:
          bestMatch = i
          bestDistance = dist
    
      return bestMatch + 16  # Los colores ANSI comienzan en 16
    
    #-- Convertir color hexadecimal a código ANSI
    proc hexToAnsi(hex: string, mode: int): string =
      let targetRGB = hexToRgb(hex)
      let ansiCode = rgbToAnsi(targetRGB)
      if mode != 1:
        return &"\e[38;5;{ansiCode}m"  # Código para color de primer plano
      else:
        return &"\e[48;5;{ansiCode}m"  # Código para color de fondo
    
    #-- Funciones para primer plano y fondo
    proc fg(hex: string): string = hexToAnsi(hex, 0)
    proc bg(hex: string): string = hexToAnsi(hex, 1)
    
    #-- Funciones para primer plano y fondo en tiempo de compilación
    proc fgx(hex: static string): string =
      static hexToAnsi(hex, 0)
    
    proc bgx(hex: static string): string =
      static hexToAnsi(hex, 1)
    
    # Ejemplo de uso:
    # const hexColor = "#FFFF00"
    # const ansiColor = hexToAnsi(hexColor, 0)
    # echo ansiColor, "¡Hola mundo!", "\e[0m"
    
    # Exportar los procedimientos relevantes
    export hexToAnsi, fg, bg, fgx, bgx
    

    Explicación de las Mejoras

    1. Generación Programática de la Paleta ANSI:

      • En lugar de listar manualmente cada color ANSI, se generan los colores del cubo 6x6x6 y los niveles de gris de forma programática. Esto no solo reduce la cantidad de código, sino que también facilita la comprensión y el mantenimiento.
    2. Definición Clara de Tipos:

      • Se define una tupla RGB para representar colores de manera clara y concisa, mejorando la legibilidad del código.
    3. Validación de Entrada:

      • La función hexToRgb ahora incluye una validación para asegurar que la cadena hexadecimal proporcionada tenga exactamente 6 caracteres después de eliminar el prefijo #. Si no es así, se lanza una excepción clara.
    4. Optimización de Cálculos:

      • La función squaredDistance utiliza directamente las tuplas RGB, lo que simplifica el cálculo de la distancia entre colores.
      • En rgbToAnsi, se recorre la paleta ANSI generada programáticamente para encontrar el color más cercano, lo que mejora la eficiencia y elimina la necesidad de una lista estática enorme.
    5. Comentarios y Estructura Mejorada:

      • Se han añadido comentarios claros para cada sección del código, facilitando la comprensión de su propósito.
      • La estructura general del código está organizada de manera lógica, siguiendo una secuencia clara de pasos desde la conversión hexadecimal hasta la generación del código ANSI correspondiente.
    6. Funciones de Tiempo de Compilación:

      • Las funciones fgx y bgx permiten realizar la conversión en tiempo de compilación cuando se proporcionan cadenas estáticas, lo que puede mejorar el rendimiento en ciertos casos.

    Ejemplo de Uso

    Para utilizar las funciones refactorizadas, puedes hacer lo siguiente:

    const hexColor = "#FF5733"
    echo fg(hexColor) & "Texto en color de primer plano" & "\e[0m"
    echo bg(hexColor) & "Texto con color de fondo" & "\e[0m"
    

    Esto imprimirá "Texto en color de primer plano" con el color especificado y "Texto con color de fondo" con el mismo color como fondo.


    Esta refactorización hace que el código sea más eficiente, más fácil de mantener y más comprensible, aprovechando las capacidades de generación programática y una estructura de datos más clara.