-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathprogress.ts
67 lines (56 loc) · 1.77 KB
/
progress.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
export class ProgressBar {
total: number;
current: number;
barLength: number;
format: string;
constructor(props: { total: number; format?: string; barLength?: number }) {
const { total, format, barLength } = props;
this.total = total;
this.current = 0;
this.barLength = barLength ?? 40;
this.format = format || "{bar} {percentage}% | {value}/{total}";
}
initialize(): void {
this.update({ current: 0 });
}
update({
current,
formatArgs,
}: {
current: number;
formatArgs?: Record<string, string>;
}): void {
this.current = current;
const ratio = this.current / this.total;
const filledBarLength = Math.round(ratio * this.barLength);
const emptyBarLength = this.barLength - filledBarLength;
const filledBar = "▓".repeat(filledBarLength);
const emptyBar = "░".repeat(emptyBarLength);
const percentage = (ratio * 100).toFixed(2);
let formattedString = this.format
.replace("{bar}", `${filledBar}${emptyBar}`)
.replace("{percentage}", percentage)
.replace("{value}", this.current.toString())
.replace("{total}", this.total.toString());
if (formatArgs) {
for (const key in formatArgs) {
if (Object.prototype.hasOwnProperty.call(formatArgs, key)) {
formattedString = formattedString.replace(
`{${key}}`,
formatArgs[key].toString()
);
}
}
}
console.log(formattedString);
}
increment({
formatArgs,
}: { formatArgs?: Record<string, string> } = {}): void {
this.update({ current: this.current + 1, formatArgs });
}
complete({ formatArgs }: { formatArgs?: Record<string, string> } = {}): void {
this.update({ current: this.total, formatArgs });
console.log("\nCompleted");
}
}