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