fix: improve size formatting functions for better robustness

- Enhanced the `formatSizeValue`, `formatMemUsage`, and `formatIOValue` functions to handle edge cases more effectively.
- Updated regex and condition checks to ensure proper parsing of input strings, improving overall reliability in formatting size values.
This commit is contained in:
Mauricio Siu
2026-04-04 21:21:41 -06:00
parent 396fb9f57f
commit f1bc3758b2

View File

@@ -1,27 +1,26 @@
/** Round a value+unit string like "2.711MiB" → "2.7 MiB" */
export const formatSizeValue = (raw: string): string => {
const match = raw.match(/^([\d.]+)\s*([A-Za-z]+)$/);
if (!match) return raw;
if (!match?.[1] || !match[2]) return raw;
const num = Number.parseFloat(match[1]);
const unit = match[2];
if (Number.isNaN(num)) return raw;
// Show 1 decimal for values >= 1, 2 decimals for tiny values
const rounded = num >= 1 ? num.toFixed(1) : num.toFixed(2);
return `${rounded} ${unit}`;
};
/** Format "2.711MiB / 7.609GiB" → "2.7 MiB / 7.6 GiB" */
export const formatMemUsage = (raw: string): string => {
const parts = raw.split("/").map((s) => s.trim());
if (parts.length !== 2) return raw;
return `${formatSizeValue(parts[0])} / ${formatSizeValue(parts[1])}`;
const [left, right] = raw.split("/").map((s) => s.trim());
if (!left || !right) return raw;
return `${formatSizeValue(left)} / ${formatSizeValue(right)}`;
};
/** Format "978B / 252B" → "978 B / 252 B" */
export const formatIOValue = (raw: string): string => {
const parts = raw.split("/").map((s) => s.trim());
if (parts.length !== 2) return raw;
return `${formatSizeValue(parts[0])} / ${formatSizeValue(parts[1])}`;
const [left, right] = raw.split("/").map((s) => s.trim());
if (!left || !right) return raw;
return `${formatSizeValue(left)} / ${formatSizeValue(right)}`;
};
/** Format "0.00%" → "0.0%", "12.345%" → "12.3%" */