-
Notifications
You must be signed in to change notification settings - Fork 94
/
ProgressBar.ts
53 lines (51 loc) · 1.6 KB
/
ProgressBar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { clearLine, cursorTo } from "readline";
const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
export class ProgressBar {
private stopped = false;
private timer: NodeJS.Timeout | null = null;
private spinnerIndex = 0;
public constructor(
private ratio = 0,
private readonly totalBlocks = 50,
) {
this.timer = setInterval(() => {
this.spinnerIndex++;
this.refresh();
}, 50);
}
public stop() {
if (this.stopped) {
throw new Error("ProgressBar already stopped");
}
this.stopped = true;
clearLine(process.stdout, 0);
cursorTo(process.stdout, 0);
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
public setRatio(ratio: number) {
this.ratio = Math.max(0, Math.min(1, ratio));
this.refresh();
}
private refresh() {
process.stdout.write(`\r${spinnerFrames[this.spinnerIndex % spinnerFrames.length]} [`);
this.drawBar();
process.stdout.write(`] ${(this.ratio * 100).toFixed(2)}%`);
}
private drawBar() {
let blocks: string;
if (this.ratio === 1) {
blocks = "█".repeat(this.totalBlocks);
} else {
const completedBlocks = Math.floor(this.ratio * this.totalBlocks);
blocks = "█".repeat(completedBlocks);
const ratioPerBlock = 1 / this.totalBlocks;
const partialBlock = Math.floor(((this.ratio % ratioPerBlock) / ratioPerBlock) * 8);
blocks += "▏▎▍▌▋▊▉█".charAt(partialBlock);
blocks += " ".repeat(this.totalBlocks - completedBlocks - 1);
}
process.stdout.write(`${blocks}`);
}
}