(milliseconds: number)
| 23 | * @returns A formatted string representing the duration. |
| 24 | */ |
| 25 | export const formatDuration = (milliseconds: number): string => { |
| 26 | if (milliseconds <= 0) { |
| 27 | return '0s'; |
| 28 | } |
| 29 | |
| 30 | if (milliseconds < 1000) { |
| 31 | return `${Math.round(milliseconds)}ms`; |
| 32 | } |
| 33 | |
| 34 | const totalSeconds = milliseconds / 1000; |
| 35 | |
| 36 | if (totalSeconds < 60) { |
| 37 | return `${totalSeconds.toFixed(1)}s`; |
| 38 | } |
| 39 | |
| 40 | const hours = Math.floor(totalSeconds / 3600); |
| 41 | const minutes = Math.floor((totalSeconds % 3600) / 60); |
| 42 | const seconds = Math.floor(totalSeconds % 60); |
| 43 | |
| 44 | const parts: string[] = []; |
| 45 | |
| 46 | if (hours > 0) { |
| 47 | parts.push(`${hours}h`); |
| 48 | } |
| 49 | if (minutes > 0) { |
| 50 | parts.push(`${minutes}m`); |
| 51 | } |
| 52 | if (seconds > 0) { |
| 53 | parts.push(`${seconds}s`); |
| 54 | } |
| 55 | |
| 56 | // If all parts are zero (e.g., exactly 1 hour), return the largest unit. |
| 57 | if (parts.length === 0) { |
| 58 | if (hours > 0) return `${hours}h`; |
| 59 | if (minutes > 0) return `${minutes}m`; |
| 60 | return `${seconds}s`; |
| 61 | } |
| 62 | |
| 63 | return parts.join(' '); |
| 64 | }; |
no outgoing calls
no test coverage detected