Passed
Pull Request — master (#15)
by Pavel
01:25
created

formatLine.ts ➔ convertSeconds   A

Complexity

Conditions 4

Size

Total Lines 22
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
dl 0
loc 22
rs 9.45
c 0
b 0
f 0
1
export default function formatLine(name: string, total_seconds: number, percent: number, use_old_format: boolean) {
2
3
  if (use_old_format) {
4
    return [
5
      cutStr(formatName(name), 10).padEnd(12),
6
      '🕓 ' + convertSeconds(total_seconds).padEnd(9),
7
      generateBarChart(percent, 24),
8
      String(percent.toFixed(1)).padStart(5) + '%',
9
    ].join(' ');
10
  }
11
12
  return [
13
    cutStr(formatName(name), 10).padEnd(15, '.'),
14
    (convertSeconds(total_seconds) + ' ').padEnd(8, '.'),
15
16
  ].join(' ') + String(percent.toFixed(1)).padStart(33, '.') + '%';
17
}
18
19
function convertSeconds(seconds: number) {
20
  const days = Math.floor(seconds / (24 * 60 * 60));
21
  seconds -= days * (24 * 60 * 60);
22
  const hours = Math.floor(seconds / (60 * 60));
23
  seconds -= hours * (60 * 60);
24
  const minutes = Math.floor(seconds / (60));
25
  seconds -= minutes * (60);
26
27
  seconds = Math.round(seconds);
28
  const result = '';
29
30
  if (days > 0) {
31
    return result + days + 'd ' + hours + 'h';
32
  }
33
  if (hours > 0) {
34
    return result + hours + 'h ' + minutes + 'm';
35
  }
36
  if (minutes > 0) {
37
    return result + minutes + 'm ' + seconds + 's';
38
  }
39
  return result + seconds + 's';
40
}
41
42
function cutStr(str: string, len: number) {
43
  return str.length > len ? str.substring(0, len - 3) + '...' : str;
44
}
45
46
function formatName(name: string) {
47
  if (name === 'Blade Template') {
48
    return 'Blade';
49
  }
50
  return name;
51
}
52
53
function generateBarChart(percent: number, size: number) {
54
  const syms = '░▏▎▍▌▋▊▉█';
55
56
  const frac = Math.floor((size * 8 * percent) / 100);
57
  const barsFull = Math.floor(frac / 8);
58
  if (barsFull >= size) {
59
    return syms.substring(8, 9).repeat(size);
60
  }
61
  const semi = frac % 8;
62
63
  return [syms.substring(8, 9).repeat(barsFull), syms.substring(semi, semi + 1)]
64
    .join('').padEnd(size, syms.substring(0, 1));
65
}