Skip to content

Commit f1bc375

Browse files
committed
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.
1 parent 396fb9f commit f1bc375

1 file changed

Lines changed: 7 additions & 8 deletions

File tree

  • apps/dokploy/components/dashboard/swarm/containers

apps/dokploy/components/dashboard/swarm/containers/utils.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
/** Round a value+unit string like "2.711MiB" → "2.7 MiB" */
22
export const formatSizeValue = (raw: string): string => {
33
const match = raw.match(/^([\d.]+)\s*([A-Za-z]+)$/);
4-
if (!match) return raw;
4+
if (!match?.[1] || !match[2]) return raw;
55
const num = Number.parseFloat(match[1]);
66
const unit = match[2];
77
if (Number.isNaN(num)) return raw;
8-
// Show 1 decimal for values >= 1, 2 decimals for tiny values
98
const rounded = num >= 1 ? num.toFixed(1) : num.toFixed(2);
109
return `${rounded} ${unit}`;
1110
};
1211

1312
/** Format "2.711MiB / 7.609GiB" → "2.7 MiB / 7.6 GiB" */
1413
export const formatMemUsage = (raw: string): string => {
15-
const parts = raw.split("/").map((s) => s.trim());
16-
if (parts.length !== 2) return raw;
17-
return `${formatSizeValue(parts[0])} / ${formatSizeValue(parts[1])}`;
14+
const [left, right] = raw.split("/").map((s) => s.trim());
15+
if (!left || !right) return raw;
16+
return `${formatSizeValue(left)} / ${formatSizeValue(right)}`;
1817
};
1918

2019
/** Format "978B / 252B" → "978 B / 252 B" */
2120
export const formatIOValue = (raw: string): string => {
22-
const parts = raw.split("/").map((s) => s.trim());
23-
if (parts.length !== 2) return raw;
24-
return `${formatSizeValue(parts[0])} / ${formatSizeValue(parts[1])}`;
21+
const [left, right] = raw.split("/").map((s) => s.trim());
22+
if (!left || !right) return raw;
23+
return `${formatSizeValue(left)} / ${formatSizeValue(right)}`;
2524
};
2625

2726
/** Format "0.00%" → "0.0%", "12.345%" → "12.3%" */

0 commit comments

Comments
 (0)