hadean-old/src/Progressbar.ts

41 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-06-14 22:03:55 -04:00
import chalk from "chalk";
2021-06-18 02:02:50 -04:00
import { getTheme } from "./ui/Theme.js";
2021-06-14 22:03:55 -04:00
2021-06-15 15:02:47 -04:00
export enum ProgressbarStyle {
indicator = 'indicator',
progress = 'progress'
}
2021-06-18 02:02:50 -04:00
export const barCache: Map<string, string> = new Map();
export function progressbar(completion: number, width: number, style: ProgressbarStyle = ProgressbarStyle.indicator) {
const cacheKey = `${completion}-${width}-${style}`;
if(barCache.has(cacheKey)) {
stats.cacheHits ++;
return barCache.get(cacheKey);
}
2021-06-15 15:02:47 -04:00
let chalkFn
if(style === ProgressbarStyle.indicator) {
2021-06-18 02:02:50 -04:00
if(completion > getTheme().progressBar.indicator.buckets[2]) chalkFn = getTheme().progressBar.indicator.excellent;
else if(completion > getTheme().progressBar.indicator.buckets[1]) chalkFn = getTheme().progressBar.indicator.normal;
else if(completion > getTheme().progressBar.indicator.buckets[0]) chalkFn = getTheme().progressBar.indicator.warning;
else chalkFn = getTheme().progressBar.indicator.critical;
2021-06-15 15:02:47 -04:00
} else if(style === ProgressbarStyle.progress) {
2021-06-18 02:02:50 -04:00
chalkFn = getTheme().progressBar.normal;
2021-06-15 15:02:47 -04:00
}
2021-06-14 22:03:55 -04:00
const chars = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
let str = '';
for(let i = 0; i < width; i ++) {
const remainder = Math.floor(Math.min(Math.max(0, (completion * width) - i), 1) * 8);
const char = chars[remainder];
2021-06-15 15:02:47 -04:00
str += chalkFn(char);
2021-06-14 22:03:55 -04:00
}
2021-06-18 02:02:50 -04:00
stats.cacheMisses ++;
barCache.set(cacheKey, str);
2021-06-14 22:03:55 -04:00
return str;
2021-06-18 02:02:50 -04:00
}
export const stats = {
cacheHits: 0,
cacheMisses: 0
2021-06-14 22:03:55 -04:00
}