@@ -5,6 +5,7 @@ const SI_PREFIXES = {
55 m : 1e-3 ,
66 '' : 1 ,
77 k : 1e3 ,
8+ K : 1e3 ,
89 M : 1e6 ,
910 G : 1e9 ,
1011 T : 1e12 ,
@@ -13,20 +14,28 @@ const SI_PREFIXES = {
1314} ;
1415
1516const SI_PREFIXES_BINARY = {
17+ '' : 1 ,
1618 Ki : 2 ** 10 ,
1719 Mi : 2 ** 20 ,
1820 Gi : 2 ** 30 ,
1921 Ti : 2 ** 40 ,
2022 Pi : 2 ** 50 ,
23+ Ei : 2 ** 60 ,
24+ } ;
25+
26+ const MEMORY_PREFIXES = {
27+ ...SI_PREFIXES ,
28+ ...SI_PREFIXES_BINARY ,
2129} ;
2230
2331/*
2432More precise round method.
25- Want 1.005 to be rounded to 1.01 we need to add Number.EPSILON to fix the float inaccuracy
33+ Fixes floating point precision issues (e.g., 1.005 rounds to 1.01)
2634 */
27- const preciseRound = ( num , places ) =>
28- Math . round ( ( num + Number . EPSILON ) * Math . pow ( 10 , places ) ) /
29- Math . pow ( 10 , places ) ;
35+ const preciseRound = ( num , places ) => {
36+ const multiplier = Math . pow ( 10 , places ) ;
37+ return Math . round ( ( num + Number . EPSILON ) * multiplier ) / multiplier ;
38+ } ;
3039
3140export function formatResourceUnit (
3241 amount = 0 ,
@@ -67,3 +76,36 @@ export function formatResourceUnit(
6776
6877 return output ;
6978}
79+
80+ export function bytesToHumanReadable ( bytes , { fixed = 0 , unit = '' } = { } ) {
81+ return formatResourceUnit ( bytes , true , { withoutSpace : true , fixed, unit } ) ;
82+ }
83+
84+ export function cpusToHumanReadable ( cpus , { fixed = 0 , unit = '' } = { } ) {
85+ return formatResourceUnit ( cpus , false , { withoutSpace : true , fixed, unit } ) ;
86+ }
87+
88+ export function getCpus ( cpuString ) {
89+ if ( ! cpuString || cpuString === '0' ) {
90+ return 0 ;
91+ }
92+
93+ const suffix = String ( cpuString ) . slice ( - 1 ) ;
94+
95+ const suffixPower = SI_PREFIXES [ suffix ] ;
96+ if ( ! suffixPower ) {
97+ return parseFloat ( cpuString ) ;
98+ }
99+
100+ const number = String ( cpuString ) . replace ( suffix , '' ) ;
101+ return number * suffixPower ;
102+ }
103+
104+ export function getBytes ( memoryStr ) {
105+ if ( ! memoryStr ) return 0 ;
106+
107+ const unit = String ( memoryStr ) . match ( / [ a - z A - Z ] + / g) ?. [ 0 ] ;
108+ const value = parseFloat ( memoryStr ) ;
109+ const bytes = value * ( MEMORY_PREFIXES [ unit ] || 1 ) ;
110+ return bytes ;
111+ }
0 commit comments