Bladeren bron

feat: Add formatDuration dayjs plugin

Owen Diffey 2 weken geleden
bovenliggende
commit
9a8668936f
2 gewijzigde bestanden met toevoegingen van 32 en 1 verwijderingen
  1. 12 0
      frontend/src/dayjs.spec.ts
  2. 20 1
      frontend/src/dayjs.ts

+ 12 - 0
frontend/src/dayjs.spec.ts

@@ -0,0 +1,12 @@
+import { faker } from "@faker-js/faker";
+import dayjs from "@/dayjs";
+
+describe("dayjs formatDuration plugin", () => {
+	test("value < 1 hour displays minutes and seconds", () => {
+		dayjs.duration(faker.number.int({ max: 359 }), "s");
+	});
+
+	test("value >= 1 hour displays hours, minutes and seconds", () => {
+		dayjs.duration(faker.number.int({ min: 360 }), "s");
+	});
+});

+ 20 - 1
frontend/src/dayjs.ts

@@ -1,9 +1,28 @@
-import dayjs, { Dayjs } from "dayjs";
+import dayjs, { Dayjs, PluginFunc } from "dayjs";
 import duration, { Duration } from "dayjs/plugin/duration";
 import relativeTime from "dayjs/plugin/relativeTime";
 import utc from "dayjs/plugin/utc";
 
+declare module "dayjs/plugin/duration" {
+	interface Duration {
+		formatDuration(): string;
+	}
+}
+
+const formatDuration: PluginFunc = (option, dayjsClass, dayjsFactory) => {
+	const durationPrototype = Object.getPrototypeOf(dayjsFactory.duration(0));
+
+	durationPrototype.formatDuration = function formatDuration() {
+		if (this.hours() === 0) {
+			return this.format("mm:ss");
+		}
+
+		return this.format("HH:mm:ss");
+	};
+};
+
 dayjs.extend(duration);
+dayjs.extend(formatDuration);
 dayjs.extend(relativeTime);
 dayjs.extend(utc);