Skip to content

Commit

Permalink
feat: format months and years utils
Browse files Browse the repository at this point in the history
  • Loading branch information
olekbaran committed Dec 18, 2024
1 parent 12db7f6 commit ce2287a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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[]) {
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/format-months.test.ts
Original file line number Diff line number Diff line change
@@ -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")
})
})
13 changes: 13 additions & 0 deletions tests/unit/format-years.test.ts
Original file line number Diff line number Diff line change
@@ -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")
})
})

0 comments on commit ce2287a

Please sign in to comment.