///|
pub fn Palette::reverse(self : Palette) -> Palette {
  let result = []
  for offset in 1..<=self.colors.length() {
    result.push(self.colors[self.colors.length() - offset])
  }
  { ..self, colors: result }
}

///|
pub fn Palette::repeat(self : Palette, times : Int) -> Palette {
  let result = []
  for _ in 0.. Palette {
  let result = []
  if self.colors.length() > 0 {
    for i in 0.. Color {
  if self.colors.length() == 0 {
    Color::rgb8(0, 0, 0)
  } else {
    let mut r = 0.0
    let mut g = 0.0
    let mut b = 0.0
    let mut a = 0.0
    for color in self.colors {
      r += color.r
      g += color.g
      b += color.b
      a += color.a
    }
    let count = self.colors.length().to_double()
    Color::rgba(r / count, g / count, b / count, a=a / count)
  }
}

///|
pub fn Palette::closest(self : Palette, target : Color) -> Color? {
  if self.colors.length() == 0 {
    None
  } else {
    let mut best = self.colors[0]
    let mut distance = color_distance(best, target)
    for color in self.colors[1:] {
      let candidate = color_distance(color, target)
      if candidate < distance {
        best = color
        distance = candidate
      }
    }
    Some(best)
  }
}

///|
fn color_distance(left : Color, right : Color) -> Double {
  let dr = left.r - right.r
  let dg = left.g - right.g
  let db = left.b - right.b
  (dr * dr + dg * dg + db * db).sqrt()
}