Barre de progression animée - Solution

Barre de progression animée - Solution

On se retrouve aujourd'hui pour la solution du précédent #KataOfTheWeek proposé par Julien en début de semaine !

La solution consiste à faire quelques calculs numériques pour déterminer où on en est dans la progression, ainsi que l'étape du curseur animé. Voici ci-dessous une implémentation :

import java.util.*;

public class MyProgressBar {

  private static final List<String> STEPS = Collections.unmodifiableList(Arrays.asList("|", "\\", "-", "/"));
  private static final String COMPLETED_STEPS_CHAR = "=";
  private static final int PERCENT_FIELD_SIZE = 10;

  private final int nbSteps;
  private final int lineLength;
  private final int totalLineLength;
  private int currentCount;

  public MyProgressBar(final int nbSteps, final int lineLength) {
    if (nbSteps <= 0 || lineLength <= 0) {
      throw new IllegalArgumentException("nbSteps and lineLength must be strictly positive");
    }
    this.nbSteps = nbSteps;
    this.lineLength = lineLength;
    this.totalLineLength = lineLength + PERCENT_FIELD_SIZE;
    this.currentCount = 0;
  }

  private void clearLine() {
    for (int i = 0; i < totalLineLength; i++) {
      System.out.print("\b");
    }
  }

  private String getCompletedStepPart() {
    var sb = new StringBuilder();
    int completedSteps = (currentCount * lineLength) / nbSteps;
    for (var i = 0; i < completedSteps; i++) {
      sb.append(COMPLETED_STEPS_CHAR);
    }
    return sb.toString();
  }

  private String getCurrentStepPart() {
    int currentStepProgress = currentCount % nbSteps;
    int stepCharIndex = currentStepProgress % STEPS.size();
    return STEPS.get(stepCharIndex);
  }

  private String getPercentage() {
    int percent = ((currentCount + 1) * 100) / nbSteps;
    return percent + "%";
  }

  private boolean isComplete() {
    return currentCount >= (nbSteps - 1);
  }

  public void increment() {
    if (isComplete()) {
      return;
    }

    clearLine();
    var line = getCompletedStepPart() + getCurrentStepPart() + " - " + getPercentage();
    System.out.print(line);

    currentCount++;
    if (isComplete()) {
      System.out.println();
    }
  }

  public static void main(String[] args) throws Throwable {
    var nbSteps = 1000;

    var bar = new MyProgressBar(nbSteps, 50);

    for (var i = 0; i < nbSteps; i++) {
      bar.increment();
      Thread.sleep(100L);
    }
  }

}

A bientôt pour un nouveau #KataOfTheWeek !