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