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
Panu Horsmalahti dcf253e7d5
Add eslint rule padding-line-between-statements (#1593)
Signed-off-by: Panu Horsmalahti <phorsmalahti@mirantis.com>
2020-12-02 09:55:52 +02:00

33 lines
856 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`;
}