What would be the cleanest way to convert an amount of seconds to the biggest unit that is not 0 and then display only the significative unit.
Input -> Expected output
1 -> 1s
61 -> 1m
120 -> 2m
3620 -> 1h
86400 -> 1day
const units = [
[1, "s"],
[60, "m"],
[60 * 60, "h"],
[60 * 60 * 24, "day"]
];
function displayTime(seconds) {
let bestUnit = units[0];
for(const unit of units) {
if(seconds >= unit[0]) {
bestUnit = unit;
}
}
const [divisor, label] = bestUnit;
return Math.floor(seconds /divisor) + label;
}
console.log(displayTime(1)); // 1s
console.log(displayTime(61)); // 1m
console.log(displayTime(120)); // 2m
console.log(displayTime(3620)); // 1h
console.log(displayTime(86400)); // 1day