Skip to content

Commit b154e22

Browse files
fix: review
1 parent 061f4a0 commit b154e22

File tree

2 files changed

+25
-14
lines changed

2 files changed

+25
-14
lines changed

src/utils/dataFormatters/__test__/formatUptime.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ describe('formatUptimeInSeconds', () => {
5252
expect(formatUptimeInSeconds(12)).toBe('12s');
5353
expect(formatUptimeInSeconds(2)).toBe('2s');
5454
});
55+
it('should correctly process negative values', () => {
56+
expect(formatUptimeInSeconds(-0)).toBe('0s');
57+
expect(formatUptimeInSeconds(-12)).toBe('-12s');
58+
expect(formatUptimeInSeconds(-1 * (12 * M + 2))).toBe('-12:02');
59+
expect(formatUptimeInSeconds(-1 * (12 * H + 12 * M + 12))).toBe('-12:12:12');
60+
expect(formatUptimeInSeconds(-1 * (12 * D + 12 * H + 12 * M + 12))).toBe(
61+
'-12d' + UNBREAKABLE_GAP + '12:12:12',
62+
);
63+
});
5564
it('should return empty placeholder on NaN', () => {
5665
expect(formatUptimeInSeconds(Number.NaN)).toBe(EMPTY_DATA_PLACEHOLDER);
5766
});

src/utils/dataFormatters/dataFormatters.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,20 +49,25 @@ export function formatUptimeInSeconds(seconds: number) {
4949
return EMPTY_DATA_PLACEHOLDER;
5050
}
5151

52-
const d = duration(seconds, 's').rescale();
52+
// duration.format() doesn't work well with negative values
53+
// negative value will be displayed like -2d -12:-58:-21
54+
// so we process positive duration and only then add sign if any
55+
const sign = seconds < 0 ? '-' : '';
56+
const d = duration(Math.abs(seconds), 's').rescale();
5357

54-
if (d.days() > 0) {
55-
return d.format(`d[${i18n('d')}${UNBREAKABLE_GAP}]hh:mm:ss`);
56-
}
58+
let value: string;
5759

58-
if (d.hours() > 0) {
59-
return d.format('h:mm:ss');
60-
}
61-
if (d.minutes() > 0) {
62-
return d.format('m:ss');
60+
if (d.days() > 0) {
61+
value = d.format(`d[${i18n('d')}${UNBREAKABLE_GAP}]hh:mm:ss`);
62+
} else if (d.hours() > 0) {
63+
value = d.format('h:mm:ss');
64+
} else if (d.minutes() > 0) {
65+
value = d.format('m:ss');
66+
} else {
67+
value = d.format(`s[${i18n('s')}]`);
6368
}
6469

65-
return d.format(`s[${i18n('s')}]`);
70+
return sign + value;
6671
}
6772

6873
export const formatMsToUptime = (ms?: number) => {
@@ -86,10 +91,7 @@ export function getDowntimeFromDateFormatted(dateFrom?: number | string, dateTo?
8691
// Prevent wrong negative uptime values
8792
diff = diff < 0 ? 0 : diff;
8893

89-
const formattedUptime = formatUptimeInSeconds(diff);
90-
91-
// Do not add sign to 0 values to prevent -0:00:00 uptime
92-
return diff === 0 ? formattedUptime : '-' + formattedUptime;
94+
return formatUptimeInSeconds(-diff);
9395
}
9496

9597
export function calcTimeDiffInSec(

0 commit comments

Comments
 (0)