Write a function formatDuration(seconds) that converts a non-negative integer of seconds into a "MM:SS" or "HH:MM:SS" string. Omit the hours portion if the duration is under one hour, and ensure all parts are zero-padded to two digits (for example, 65 becomes "01:05" and 3661 becomes "01:01:01").
function formatDuration(seconds) {
// Your code here
}
Rules:
Assume seconds is always an integer >= 0
Single-digit values must be zero-padded (e.g. 5 seconds → “00:05”)
Return “HH:MM:SS” only when seconds >= 3600, otherwise return “MM:SS”
Post your solution as a reply. Answer goes up in about a day.
Challenge solution: The solution converts total seconds into hours, minutes, and seconds, then formats these components with zero-padding based on the total duration.
Why:
This function first defines a helper pad function to ensure two-digit zero-padding for any number. It then calculates hours, minutes, and remaining seconds using integer division and modulo operations. Finally, it conditionally formats the output string to ‘HH:MM:SS’ if the total seconds are 3600 or more, otherwise it returns ‘MM:SS’, ensuring all parts are correctly padded.