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 {
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();
25 if (units[unit] !== '') {
26 result = `${result} ${units[unit]}`;
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
36 * @returns Returns the given value in bytes without any unit appended or the defined error value
37 * in case xof an error.
39 toBytes(value: string, error_value: number = null): number | null {
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);
46 let bytes = parseFloat(m[1]);
47 if (_.isString(m[3])) {
48 bytes = bytes * Math.pow(base, units.indexOf(m[3].toLowerCase()[0]));
50 return Math.round(bytes);
54 * Converts `x ms` to `x` (currently) or `0` if the conversion fails
56 toMilliseconds(value: string): number {
57 const pattern = /^\s*(\d+)\s*(ms)?\s*$/i;
58 const testResult = pattern.exec(value);
60 if (testResult !== null) {
61 return +testResult[1];
68 * Converts `x IOPS` to `x` (currently) or `0` if the conversion fails
70 toIops(value: string): number {
71 const pattern = /^\s*(\d+)\s*(IOPS)?\s*$/i;
72 const testResult = pattern.exec(value);
74 if (testResult !== null) {
75 return +testResult[1];