Progressbar made of characters

Viewed 58

I have been trying to get a progress bar representation that looks like this: The user has to enter an input, and as of the input, the loop will run and get to a 100%.

Enter State: 70

[#######   ]  70 %
[########  ]  80 %
[######### ]  90 %
[##########] 100 %

Here is what I have ade so far, but I am stuck now:

let hashtag = "";
for (let i = 1; i <= 3; i++) {
  hashtag += "#";
}

console.log(
  "[" + hashtag + " ",
  " ",
  " ",
  " ",
  " ",
  " ",
  " " + "]" + " " + "30%"
);

Any ideas of how to solve this problem? I a a total beginner, please go easy on me" :)

1 Answers

const generateOutput = (pct, width = 10) => {
  const flr = Math.floor(pct * width / 100);
  const str = "#".repeat(flr).padEnd(width, " ");
  return `[${str}] ${pct}%`;
};

// Example 90% (width 10)
console.log(generateOutput(90));

// Example 80% (width 30)
console.log(generateOutput(80, 30));

Given the above Formatted String generator, if you need a loop that will change the output:

const generateOutput = (pct, width = 10) => {
  const flr = Math.floor(pct * width / 100);
  const str = "#".repeat(flr).padEnd(width, "-");
  return `[${str}] ${pct}%`;
};


const EL_output = document.querySelector("#output");
const step  = 1;  // Increment step
const width = 30; // Progressbar width
const time  = 80; // Timeout ms

const progress = (val) => {
  EL_output.textContent = generateOutput(val, width);
  if (val >= 100) return; // Stop 
  setTimeout(() => progress(val += step), time);
};

// DEMO TIME! Start at 30
progress(30);
#output {white-space: pre;}
<code id="output"></code>

Related