Use a simpler approach

This commit is contained in:
user1823 2025-06-18 10:47:27 +05:30 committed by GitHub
parent 950f26c16b
commit 53f83d9cd3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -36,25 +36,21 @@ export function unitName(unit: TimespanUnit): string {
} }
} }
export function naturalUnit(secs: number, maxUnit: TimespanUnit = TimespanUnit.Years): TimespanUnit { export function naturalUnit(secs: number): TimespanUnit {
secs = Math.abs(secs); secs = Math.abs(secs);
const thresholds = [ if (secs < MINUTE) {
{ unit: TimespanUnit.Years, min: YEAR }, return TimespanUnit.Seconds;
{ unit: TimespanUnit.Months, min: MONTH }, } else if (secs < HOUR) {
{ unit: TimespanUnit.Days, min: DAY }, return TimespanUnit.Minutes;
{ unit: TimespanUnit.Hours, min: HOUR }, } else if (secs < DAY) {
{ unit: TimespanUnit.Minutes, min: MINUTE }, return TimespanUnit.Hours;
{ unit: TimespanUnit.Seconds, min: 0 }, } else if (secs < MONTH) {
]; return TimespanUnit.Days;
for (const { unit, min } of thresholds) { } else if (secs < YEAR) {
if (unit > maxUnit) { return TimespanUnit.Months;
continue; } else {
} return TimespanUnit.Years;
if (secs >= min) {
return unit;
}
} }
return TimespanUnit.Seconds;
} }
/** Number of seconds in a given unit. */ /** Number of seconds in a given unit. */
@ -156,7 +152,7 @@ export function timeSpan(
precise = true, precise = true,
maxUnit: TimespanUnit = TimespanUnit.Years, maxUnit: TimespanUnit = TimespanUnit.Years,
): string { ): string {
const unit = naturalUnit(seconds, maxUnit); const unit = Math.min(naturalUnit(seconds), maxUnit);
let amount = unitAmount(unit, seconds); let amount = unitAmount(unit, seconds);
if (!precise && unit < TimespanUnit.Months) { if (!precise && unit < TimespanUnit.Months) {
amount = Math.round(amount); amount = Math.round(amount);