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 * Converts a value from one set of units to another using a conversion factor
33 * @param n The value to be converted
34 * @param units The data units of the value
35 * @param targetedUnits The wanted data units to convert to
36 * @param conversionFactor The factor of convesion
37 * @param unitsArray An ordered array containing the data units
38 * @param decimals The number of decimals on the returned value
39 * @returns Returns a string of the given value formated to the targeted data units.
44 targetedUnits: string,
45 conversionFactor: number,
55 const unitsArrayLowerCase = unitsArray.map((str) => str.toLowerCase());
57 !unitsArrayLowerCase.includes(units.toLowerCase()) ||
58 !unitsArrayLowerCase.includes(targetedUnits.toLowerCase())
60 return `${n} ${units}`;
63 unitsArrayLowerCase.indexOf(units.toLowerCase()) -
64 unitsArrayLowerCase.indexOf(targetedUnits.toLocaleLowerCase());
67 ? n * Math.pow(conversionFactor, index)
68 : n / Math.pow(conversionFactor, Math.abs(index));
69 let result = _.round(convertedN, decimals).toString();
70 result = `${result} ${targetedUnits}`;
75 * Convert the given value into bytes.
76 * @param {string} value The value to be converted, e.g. 1024B, 10M, 300KiB or 1ZB.
77 * @param error_value The value returned in case the regular expression did not match. Defaults to
79 * @returns Returns the given value in bytes without any unit appended or the defined error value
80 * in case xof an error.
82 toBytes(value: string, error_value: number = null): number | null {
84 const units = ['b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y'];
85 const m = RegExp('^(\\d+(.\\d+)?) ?([' + units.join('') + ']?(b|ib|B/s)?)?$', 'i').exec(value);
89 let bytes = parseFloat(m[1]);
90 if (_.isString(m[3])) {
91 bytes = bytes * Math.pow(base, units.indexOf(m[3].toLowerCase()[0]));
93 return Math.round(bytes);
97 * Converts `x ms` to `x` (currently) or `0` if the conversion fails
99 toMilliseconds(value: string): number {
100 const pattern = /^\s*(\d+)\s*(ms)?\s*$/i;
101 const testResult = pattern.exec(value);
103 if (testResult !== null) {
104 return +testResult[1];
111 * Converts `x IOPS` to `x` (currently) or `0` if the conversion fails
113 toIops(value: string): number {
114 const pattern = /^\s*(\d+)\s*(IOPS)?\s*$/i;
115 const testResult = pattern.exec(value);
117 if (testResult !== null) {
118 return +testResult[1];