]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | import { Injectable } from '@angular/core'; |
2 | ||
f67539c2 | 3 | import _ from 'lodash'; |
11fdf7f2 | 4 | |
11fdf7f2 | 5 | @Injectable({ |
81eedcae | 6 | providedIn: 'root' |
11fdf7f2 TL |
7 | }) |
8 | export class FormatterService { | |
11fdf7f2 TL |
9 | format_number(n: any, divisor: number, units: string[], decimals: number = 1): string { |
10 | if (_.isString(n)) { | |
11 | n = Number(n); | |
12 | } | |
13 | if (!_.isNumber(n)) { | |
14 | return '-'; | |
15 | } | |
1e59de90 TL |
16 | if (_.isNaN(n)) { |
17 | return 'N/A'; | |
18 | } | |
11fdf7f2 TL |
19 | let unit = n < 1 ? 0 : Math.floor(Math.log(n) / Math.log(divisor)); |
20 | unit = unit >= units.length ? units.length - 1 : unit; | |
21 | let result = _.round(n / Math.pow(divisor, unit), decimals).toString(); | |
22 | if (result === '') { | |
23 | return '-'; | |
24 | } | |
25 | if (units[unit] !== '') { | |
26 | result = `${result} ${units[unit]}`; | |
27 | } | |
28 | return result; | |
29 | } | |
30 | ||
31 | /** | |
32 | * Convert the given value into bytes. | |
33 | * @param {string} value The value to be converted, e.g. 1024B, 10M, 300KiB or 1ZB. | |
34 | * @param error_value The value returned in case the regular expression did not match. Defaults to | |
35 | * null. | |
36 | * @returns Returns the given value in bytes without any unit appended or the defined error value | |
37 | * in case xof an error. | |
38 | */ | |
9f95a23c | 39 | toBytes(value: string, error_value: number = null): number | null { |
11fdf7f2 TL |
40 | const base = 1024; |
41 | const units = ['b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y']; | |
42 | const m = RegExp('^(\\d+(.\\d+)?) ?([' + units.join('') + ']?(b|ib|B/s)?)?$', 'i').exec(value); | |
43 | if (m === null) { | |
44 | return error_value; | |
45 | } | |
46 | let bytes = parseFloat(m[1]); | |
47 | if (_.isString(m[3])) { | |
48 | bytes = bytes * Math.pow(base, units.indexOf(m[3].toLowerCase()[0])); | |
49 | } | |
50 | return Math.round(bytes); | |
51 | } | |
52 | ||
53 | /** | |
54 | * Converts `x ms` to `x` (currently) or `0` if the conversion fails | |
55 | */ | |
56 | toMilliseconds(value: string): number { | |
57 | const pattern = /^\s*(\d+)\s*(ms)?\s*$/i; | |
58 | const testResult = pattern.exec(value); | |
59 | ||
60 | if (testResult !== null) { | |
61 | return +testResult[1]; | |
62 | } | |
63 | ||
64 | return 0; | |
65 | } | |
66 | ||
67 | /** | |
68 | * Converts `x IOPS` to `x` (currently) or `0` if the conversion fails | |
69 | */ | |
70 | toIops(value: string): number { | |
71 | const pattern = /^\s*(\d+)\s*(IOPS)?\s*$/i; | |
72 | const testResult = pattern.exec(value); | |
73 | ||
74 | if (testResult !== null) { | |
75 | return +testResult[1]; | |
76 | } | |
77 | ||
78 | return 0; | |
79 | } | |
80 | } |