Skip to content

Instantly share code, notes, and snippets.

@Sv443
Last active November 20, 2024 23:13
Show Gist options
  • Save Sv443/5775ac773772a112748cf5ce21aa94ba to your computer and use it in GitHub Desktop.
Save Sv443/5775ac773772a112748cf5ce21aa94ba to your computer and use it in GitHub Desktop.
TypeScript / JavaScript ASCII progress bar function using semi-opaque block characters for extra detail
// Example for 30.7% and length = 14: ████░─────────
// (to use this in JS, remove the `: type` annotations on line 9)
/**
* Generates an ASCII progress bar with the given percentage and max length - uses opaque characters for extra detail
* @param percentage A number from 0 to 100
* @param barLength The length of the progress bar in characters
*/
function generateAsciiProgressBar(percentage: number, barLength: number) {
const fullBlock = "█";
const threeQuarterBlock = "▓";
const halfBlock = "▒";
const quarterBlock = "░";
const emptyBlock = "─";
if(percentage === 100)
return fullBlock.repeat(barLength);
const filledLength = Math.floor((percentage / 100) * barLength);
const remainingPercentage = percentage / 10 * barLength - filledLength;
let lastBlock = "";
if(remainingPercentage >= 0.75)
lastBlock = threeQuarterBlock;
else if(remainingPercentage >= 0.5)
lastBlock = halfBlock;
else if (remainingPercentage >= 0.25)
lastBlock = quarterBlock;
const filledBar = fullBlock.repeat(filledLength);
const emptyBar = emptyBlock.repeat(barLength - filledLength - (lastBlock ? 1 : 0));
return `${filledBar}${lastBlock}${emptyBar}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment