From ce2287ae9d0ee7a38a9ad1b1bfc8df81fa36b650 Mon Sep 17 00:00:00 2001 From: Olek Baran Date: Wed, 18 Dec 2024 23:53:26 +0100 Subject: [PATCH] feat: format months and years utils --- lib/utils.ts | 16 +++++++++++----- tests/unit/format-months.test.ts | 13 +++++++++++++ tests/unit/format-years.test.ts | 13 +++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 tests/unit/format-months.test.ts create mode 100644 tests/unit/format-years.test.ts diff --git a/lib/utils.ts b/lib/utils.ts index bbd80c5..5b23045 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -33,6 +33,14 @@ export function formatDate(input: string | number | Date): string { }) } +export function formatMonths(months: number) { + return `${months} mo${months > 1 ? "s" : ""}` +} + +export function formatYears(years: number) { + return `${years} yr${years > 1 ? "s" : ""}` +} + export function calculateYearsOfExperience(workExperience: WorkExperience[]) { const currentDate = new Date() @@ -70,19 +78,17 @@ export function calculateDatesDifference( (endDate.getDate() >= startDate.getDate() ? 1 : 0) if (monthsDifference < 12) { - return `${monthsDifference} mo${monthsDifference > 1 ? "s" : ""}` + return formatMonths(monthsDifference) } const yearsDifference = Math.floor(monthsDifference / 12) const remainingMonths = monthsDifference % 12 if (remainingMonths === 0) { - return `${yearsDifference} yr${yearsDifference > 1 ? "s" : ""}` + return formatYears(yearsDifference) } - return `${yearsDifference} yr${ - yearsDifference > 1 ? "s" : "" - } ${remainingMonths} mo${remainingMonths > 1 ? "s" : ""}` + return `${formatYears(yearsDifference)} ${formatMonths(remainingMonths)}` } export function groupWorkExperience(workExperience: WorkExperience[]) { diff --git a/tests/unit/format-months.test.ts b/tests/unit/format-months.test.ts new file mode 100644 index 0000000..f77439d --- /dev/null +++ b/tests/unit/format-months.test.ts @@ -0,0 +1,13 @@ +import { formatMonths } from "@/lib/utils" + +describe("formatMonths", () => { + it("should format single month without plural suffix", () => { + const result = formatMonths(1) + expect(result).toBe("1 mo") + }) + + it("should format multiple months with plural suffix", () => { + const result = formatMonths(2) + expect(result).toBe("2 mos") + }) +}) diff --git a/tests/unit/format-years.test.ts b/tests/unit/format-years.test.ts new file mode 100644 index 0000000..c31aca1 --- /dev/null +++ b/tests/unit/format-years.test.ts @@ -0,0 +1,13 @@ +import { formatYears } from "@/lib/utils" + +describe("formatYears", () => { + it("should format single year without plural suffix", () => { + const result = formatYears(1) + expect(result).toBe("1 yr") + }) + + it("should format multiple years with plural suffix", () => { + const result = formatYears(2) + expect(result).toBe("2 yrs") + }) +})