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