* feat: remove moment dependency * refactor * add tests * small format * rename argumentpull/2493/head
parent
014ba07aea
commit
5b5beadf4d
@ -0,0 +1,60 @@
|
||||
import {
|
||||
divisorDay,
|
||||
divisorHour,
|
||||
divisorMinute,
|
||||
divisorSecond,
|
||||
formatTime,
|
||||
} from "./time";
|
||||
|
||||
describe("formatTime", () => {
|
||||
it("should format day hour minute and second", () => {
|
||||
const uptimeInSeconds = 3661;
|
||||
|
||||
const formattedTime = formatTime(uptimeInSeconds, [
|
||||
{ unit: "d", divisor: divisorDay },
|
||||
{ unit: "h", divisor: divisorHour },
|
||||
{ unit: "m", divisor: divisorMinute },
|
||||
{ unit: "s", divisor: divisorSecond },
|
||||
]);
|
||||
|
||||
expect(formattedTime).toBe("0d 01:01:01");
|
||||
});
|
||||
|
||||
it("should format multiple digits of days", () => {
|
||||
const uptimeInSeconds = 50203661;
|
||||
|
||||
const formattedTime = formatTime(uptimeInSeconds, [
|
||||
{ unit: "d", divisor: divisorDay },
|
||||
{ unit: "h", divisor: divisorHour },
|
||||
{ unit: "m", divisor: divisorMinute },
|
||||
{ unit: "s", divisor: divisorSecond },
|
||||
]);
|
||||
|
||||
expect(formattedTime).toBe("581d 25:27:41");
|
||||
});
|
||||
|
||||
it("should format time day hour minute", () => {
|
||||
const uptimeInSeconds = 3661;
|
||||
|
||||
const formattedTime = formatTime(uptimeInSeconds, [
|
||||
{ unit: "d", divisor: divisorDay },
|
||||
{ unit: "h", divisor: divisorHour },
|
||||
{ unit: "m", divisor: divisorMinute },
|
||||
]);
|
||||
|
||||
expect(formattedTime).toBe("0d 01:01");
|
||||
});
|
||||
|
||||
it("should format zero uptime", () => {
|
||||
const uptimeInSeconds = 0;
|
||||
|
||||
const formattedTime = formatTime(uptimeInSeconds, [
|
||||
{ unit: "d", divisor: divisorDay },
|
||||
{ unit: "h", divisor: divisorHour },
|
||||
{ unit: "m", divisor: divisorMinute },
|
||||
{ unit: "s", divisor: divisorSecond },
|
||||
]);
|
||||
|
||||
expect(formattedTime).toBe("0d 00:00:00");
|
||||
});
|
||||
});
|
@ -0,0 +1,29 @@
|
||||
interface TimeFormat {
|
||||
unit: string;
|
||||
divisor: number;
|
||||
}
|
||||
|
||||
export const divisorDay = 24 * 60 * 60;
|
||||
export const divisorHour = 60 * 60;
|
||||
export const divisorMinute = 60;
|
||||
export const divisorSecond = 1;
|
||||
|
||||
export const formatTime = (
|
||||
timeInSeconds: number,
|
||||
formats: TimeFormat[],
|
||||
): string =>
|
||||
formats.reduce(
|
||||
(formattedTime: string, { unit, divisor }: TimeFormat, index: number) => {
|
||||
const timeValue: number =
|
||||
index === 0
|
||||
? Math.floor(timeInSeconds / divisor)
|
||||
: Math.floor(timeInSeconds / divisor) % 60;
|
||||
return (
|
||||
formattedTime +
|
||||
(index === 0
|
||||
? `${timeValue}${unit} `
|
||||
: `${timeValue.toString().padStart(2, "0")}${index < formats.length - 1 ? ":" : ""}`)
|
||||
);
|
||||
},
|
||||
"",
|
||||
);
|
Loading…
Reference in new issue