getAoX method

Future<String> getAoX(
  1. List<TimeTraining> timesList,
  2. int numAvg
)

Metodo para calcular la media de X tiempos (AoX) de una sesión.

Este metodo calcula la media de los X tiempos más recientes registrados en la sesión, eliminando el mejor y el peor tiempo. Se filtra los DNF ya que si contiene uno la media se establecerá como peor tiempo, pero si tiene más entonces la media se establece como DNF.

Parametros:

  • timesList: Lista de tiempos TimeTraining registrados.
  • numAvg: Número de tiempos que se usan para calcular la media.

Retorna:

  • String: Tiempo medio en formato "mm:ss.ss" si hay suficientes tiempos.
  • "--:--.--" si hay menos tiempos de los necesarios para calcular la media.

Implementation

Future<String> getAoX(List<TimeTraining> timesList, int numAvg) async {
  if (timesList.length < numAvg) {
    return "--:--.--";
  } // SI NO HAY LOS x TIEMPOS PARA HACER ESA MEDIA, DEVUELVE EL STRING POR DEFECTO

  double avgTimeInSeconds = 0.0;

  // ORDENAMOS LA LISTA POR FECHA MAS RECIENTE
  timesList.sort((a, b) {
    // CONVERTIMOS LAS FECHAS A DATETIME PARA HACER LA COMPARACION
    DateTime dateA = DateTime.parse(a.registrationDate);
    DateTime dateB = DateTime.parse(b.registrationDate);

    // CompareTo PARA QUE EL MAS RECIENTE ESTE PRIMERO
    return dateB.compareTo(dateA); // SE ORDENA DE MAS RECIENTE
  });

  // COGEMOS SOLO LOS x TIEMPOS MAS RECIENTES QUE QUEREMOS USAR EN LA MEDIA
  // (.take devuelve los primeros numAvg elementos de la lista)
  List<TimeTraining> recentTimes = timesList.take(numAvg).toList();

  // FILTRAMOS LOS DNF (EL DNF SE CONSIDERA EL PEOR TIEMPO)
  recentTimes.removeWhere((time) => time.penalty == "DNF");

  // SI ELIMINA MAS DE UN TIEMPO POR DNF, LA MEDIA SE QUEDA EN DNF
  if (recentTimes.length < numAvg - 1) {
    return "DNF";
  }

  // ORDENAMOS POR TIEMPO PARA SACAR EL MEJOR Y EL PEOR
  recentTimes.sort((a, b) => a.timeInSeconds.compareTo(b.timeInSeconds));

  // QUITAMOS EL MEJOR TIEMPO (PRIMERO) Y EL PEOR TIEMPO (ULTIMO)
  recentTimes.removeAt(0); // MEJOR
  recentTimes.removeLast(); // PEOR

  for (var time in recentTimes) {
    avgTimeInSeconds += time.timeInSeconds;
  } // SUMAMOS LOS TIEMPOS RESTANTES

  // HACEMOS LA MEDIA DIVIDIENDO POR LOS TIEMPOS QUE QUEDAN
  avgTimeInSeconds = avgTimeInSeconds / recentTimes.length;

  // SACAMOS MINUTOS Y SEGUNDOS
  int minutes = avgTimeInSeconds ~/ 60; // MINUTOS
  double seconds = avgTimeInSeconds % 60; // SEGUNDOS

  // DEVOLVEMOS EL RESULTADO FORMATEADO mm:ss.ss
  // (se usa padLeft para asegura que el string tenga siempre 5 caracteres
  // rellenando con ceros a la izquierda si hace falta. Y se redondea a 2
  // decimales)
  return "$minutes:${seconds.toStringAsFixed(2).padLeft(5, '0')}";
}