mirror of
https://github.com/maziggy/bambuddy.git
synced 2026-10-02 12:15:36 +02:00
Extract repeated helper functions from components into shared utils (colors.ts, date.ts, file.ts) to reduce duplication: - isLightColor, parseFilamentColor, hexToColorName → utils/colors.ts - formatMediaTime, formatDurationFromHours → utils/date.ts - formatFileSize guard hardened for NaN/negative → utils/file.ts - formatBytes (ToastContext), formatTime (Timelapse*) deduplicated Functions with subtly different behavior are intentionally kept local (formatFilament, formatStorageSize, formatBytes, formatUptime, formatDateTime, formatDate, formatTimeAgo) to preserve exact UI output.
21 lines
630 B
TypeScript
21 lines
630 B
TypeScript
/**
|
|
* Formats a byte count into a human-readable string (e.g. `1.5 MB`).
|
|
*
|
|
* @param bytes - The number of bytes to format.
|
|
* @returns A formatted string with the appropriate unit (B, KB, MB, GB, or TB).
|
|
*/
|
|
export function formatFileSize(bytes: number): string {
|
|
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
|
|
|
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
const k = 1024;
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
|
|
const size = bytes / Math.pow(k, i);
|
|
|
|
// No decimals for bytes, 1 decimal for larger units
|
|
return i === 0
|
|
? `${size} ${units[i]}`
|
|
: `${size.toFixed(1)} ${units[i]}`;
|
|
}
|