refactor: cleaner and faster time formatter

This commit is contained in:
Hero
2025-09-24 07:44:46 +08:00
committed by Hundrec
parent 26b253d8ca
commit 3486fe3dde
+21 -30
View File
@@ -35,37 +35,28 @@ class Postbuild
static function format(time:Float, decimals:Int = 1):String
{
var units = [
{name: "day", secs: 86400},
{name: "hour", secs: 3600},
{name: "minute", secs: 60},
{name: "second", secs: 1}
];
var parts:Array<String> = [];
var remaining:Float = time;
for (unit in units)
{
var value:Float;
if (unit.name == "second")
var units = [
{name: "day", secs: 86400},
{name: "hour", secs: 3600},
{name: "minute", secs: 60},
{name: "second", secs: 1}
];
var parts:Array<String> = [];
var remaining:Float = time;
var factor = Math.pow(10, decimals); // compute once because the old code was computing it twice.
for (u in units)
{
// handle seconds with decimals
value = Math.round(remaining * Math.pow(10, decimals)) / Math.pow(10, decimals);
var value:Float = (u.name == "second") ? Math.round(remaining * factor) / factor : Math.floor(remaining / u.secs);
if (u.name != "second")
remaining %= u.secs;
if (value > 0 || (u.name == "second" && parts.length == 0))
parts.push('${value} ${u.name}${value == 1 ? "" : "s"}');
}
else
{
value = Math.floor(remaining / unit.secs);
remaining %= unit.secs;
}
//
if (value > 0 || (unit.name == "second" && parts.length == 0))
{
parts.push('${value} ${unit.name}${value == 1 ? "" : "s"}');
}
}
return parts.join(" ");
return parts.join(" ");
}
}