1 import { Injectable } from '@angular/core';
3 import _ from 'lodash';
8 export class FormatterService {
9 format_number(n: any, divisor: number, units: string[], decimals: number = 1): string {
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();
22 if (units[unit] !== '') {
23 result = `${result} ${units[unit]}`;
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
33 * @returns Returns the given value in bytes without any unit appended or the defined error value
34 * in case xof an error.
36 toBytes(value: string, error_value: number = null): number | null {
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);
43 let bytes = parseFloat(m[1]);
44 if (_.isString(m[3])) {
45 bytes = bytes * Math.pow(base, units.indexOf(m[3].toLowerCase()[0]));
47 return Math.round(bytes);
51 * Converts `x ms` to `x` (currently) or `0` if the conversion fails
53 toMilliseconds(value: string): number {
54 const pattern = /^\s*(\d+)\s*(ms)?\s*$/i;
55 const testResult = pattern.exec(value);
57 if (testResult !== null) {
58 return +testResult[1];
65 * Converts `x IOPS` to `x` (currently) or `0` if the conversion fails
67 toIops(value: string): number {
68 const pattern = /^\s*(\d+)\s*(IOPS)?\s*$/i;
69 const testResult = pattern.exec(value);
71 if (testResult !== null) {
72 return +testResult[1];