Explore: Fix units overflow for trace durations (#108515)
* fix: Avoid redundant formatting Avoid formatting `secondaryUnitString` if it's not going to be used. Signed-off-by: martincostello <martin@martincostello.com> * fix: Fix date formatting when rounded Fix issue where rounded secondary units would not be carried over to the primary unit when they are a whole multiple of that unit (e.g. `"4m 60s"` instead of `"5m"`). Signed-off-by: martincostello <martin@martincostello.com> --------- Signed-off-by: martincostello <martin@martincostello.com>
This commit is contained in:
@@ -58,4 +58,9 @@ describe('formatDuration', () => {
|
||||
const input = 0;
|
||||
expect(formatDuration(input)).toBe('0μs');
|
||||
});
|
||||
|
||||
it('skips secondary units that are a whole multiple of the primary unit', () => {
|
||||
const input = 299898037.75;
|
||||
expect(formatDuration(input)).toBe('5m');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,9 +95,24 @@ export function formatDuration(duration: number): string {
|
||||
return `${_round(duration / primaryUnit.microseconds, 2)}${primaryUnit.unit}`;
|
||||
}
|
||||
|
||||
const primaryValue = Math.floor(duration / primaryUnit.microseconds);
|
||||
let primaryValue = Math.floor(duration / primaryUnit.microseconds);
|
||||
let secondaryValue = (duration / secondaryUnit.microseconds) % primaryUnit.ofPrevious;
|
||||
const secondaryValueRounded = Math.round(secondaryValue);
|
||||
|
||||
// Handle rollover case before rounding (e.g., 60s should become 1m, not 0m 60s)
|
||||
if (secondaryValueRounded === primaryUnit.ofPrevious) {
|
||||
primaryValue += 1;
|
||||
secondaryValue = 0;
|
||||
} else {
|
||||
secondaryValue = secondaryValueRounded;
|
||||
}
|
||||
|
||||
const primaryUnitString = `${primaryValue}${primaryUnit.unit}`;
|
||||
const secondaryValue = Math.round((duration / secondaryUnit.microseconds) % primaryUnit.ofPrevious);
|
||||
|
||||
if (secondaryValue === 0) {
|
||||
return primaryUnitString;
|
||||
}
|
||||
|
||||
const secondaryUnitString = `${secondaryValue}${secondaryUnit.unit}`;
|
||||
return secondaryValue === 0 ? primaryUnitString : `${primaryUnitString} ${secondaryUnitString}`;
|
||||
return `${primaryUnitString} ${secondaryUnitString}`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user