Skip to content

Commit a3b3c1c

Browse files
VIA-630 MD/DB: Move calculateAge to the file date and its test file
1 parent 0aa6f87 commit a3b3c1c

File tree

4 files changed

+55
-56
lines changed

4 files changed

+55
-56
lines changed

src/utils/age.test.ts

Lines changed: 0 additions & 47 deletions
This file was deleted.

src/utils/age.ts

Lines changed: 0 additions & 9 deletions
This file was deleted.

src/utils/date.test.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { UtcDateFromStringSchema, UtcDateTimeFromStringSchema } from "@src/utils/date";
2+
import { calculateAge } from "@src/utils/date";
23

34
describe("utils-date", () => {
45
describe("UtcDateFromStringSchema", () => {
@@ -63,4 +64,49 @@ describe("utils-date", () => {
6364
}).toThrow();
6465
});
6566
});
67+
describe("calculateAge", () => {
68+
beforeEach(() => {
69+
jest.useFakeTimers().setSystemTime(new Date("2025-01-15T00:00:00.000Z").getTime());
70+
});
71+
72+
it("should return age based on birthdate", () => {
73+
const birthdate = "2011-11-01";
74+
75+
const result = calculateAge(birthdate);
76+
77+
expect(result).toEqual(13);
78+
});
79+
80+
it("should return age of previous year if tomorrow is their birthday", () => {
81+
const birthdate = "1987-01-16";
82+
83+
const result = calculateAge(birthdate);
84+
85+
expect(result).toEqual(37);
86+
});
87+
88+
it("should return updated age if today is their birthday", () => {
89+
const birthdate = "1987-01-15";
90+
91+
const result = calculateAge(birthdate);
92+
93+
expect(result).toEqual(38);
94+
});
95+
96+
it("should return age of this year if birthday was yesterday", () => {
97+
const birthdate = "1987-01-14";
98+
99+
const result = calculateAge(birthdate);
100+
101+
expect(result).toEqual(38);
102+
});
103+
104+
it("should throw if birthdate is invalid", () => {
105+
const birthdate = "1987-13-17";
106+
107+
expect(() => {
108+
calculateAge(birthdate);
109+
}).toThrow();
110+
});
111+
});
66112
});

src/utils/date.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { Age } from "@src/utils/auth/types";
2+
import { differenceInYears } from "date-fns";
13
import { z } from "zod";
24

35
export const UtcDateFromStringSchema = z
@@ -28,3 +30,10 @@ export const UtcDateTimeFromStringSchema = z.iso
2830

2931
return date;
3032
});
33+
34+
export const calculateAge = (date: string): Age => {
35+
const today: Date = new Date();
36+
const birthDate: Date = UtcDateFromStringSchema.parse(date);
37+
38+
return differenceInYears(today, birthDate) as Age;
39+
};

0 commit comments

Comments
 (0)