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