1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/renderer/utils/convertMemory.ts
Sebastian Malton 0c3be9bbae
Fix Resource Quota Rendering (#624)
* add parsing of quota values which are non-numeric in the general case

* add unit tests

Signed-off-by: Sebastian Malton <smalton@mirantis.com>

Co-authored-by: Sebastian Malton <smalton@mirantis.com>
2020-08-04 13:14:02 -04:00

31 lines
845 B
TypeScript

// Helper to convert memory from units Ki, Mi, Gi, Ti, Pi to bytes and vise versa
const base = 1024
const suffixes = ['K', 'M', 'G', 'T', 'P', 'E'] // Equivalents: Ki, Mi, Gi, Ti, Pi, Ei
export function unitsToBytes(value: string) {
if (!suffixes.some(suffix => value.includes(suffix))) {
return parseFloat(value)
}
const suffix = value.replace(/[0-9]|i|\./g, '');
const index = suffixes.indexOf(suffix);
return parseInt(
(parseFloat(value) * Math.pow(base, index + 1)).toFixed(1)
)
}
export function bytesToUnits(bytes: number, precision = 1) {
const sizes = ["B", ...suffixes]
const index = Math.floor(Math.log(bytes) / Math.log(base))
if (!bytes) {
return "N/A"
}
if (index === 0) {
return `${bytes}${sizes[index]}`
}
return `${(bytes / (1024 ** index)).toFixed(precision)}${sizes[index]}i`
}