Skip to content

Commit 7f8cfb1

Browse files
VIA-630 MD/DB: calculate age based on birthdate
1 parent a1e4aa3 commit 7f8cfb1

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed

package-lock.json

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
"@types/aws-lambda": "^8.10.159",
7878
"axios": "^1.13.2",
7979
"cheerio": "^1.1.2",
80+
"date-fns": "^4.1.0",
8081
"dotenv": "^17.2.3",
8182
"es-toolkit": "^1.42.0",
8283
"isomorphic-dompurify": "^2.33.0",

src/utils/age.test.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { calculateAge } from "./age";
2+
3+
describe("calculateAge", () => {
4+
beforeEach(() => {
5+
jest.useFakeTimers().setSystemTime(new Date("2025-01-15T00:00:00.000Z").getTime());
6+
});
7+
8+
it("should return age based on birthdate", () => {
9+
const birthdate = "2011-11-01";
10+
11+
const result = calculateAge(birthdate);
12+
13+
expect(result).toEqual(13);
14+
});
15+
16+
it("should return age of previous year if upcoming birthday is this month", () => {
17+
const birthdate = "1987-01-17";
18+
19+
const result = calculateAge(birthdate);
20+
21+
expect(result).toEqual(37);
22+
});
23+
24+
it("should return updated age if today is their birthday", () => {
25+
const birthdate = "1987-01-15";
26+
27+
const result = calculateAge(birthdate);
28+
29+
expect(result).toEqual(38);
30+
});
31+
32+
it("should return age of this year if birthday was yesterday", () => {
33+
const birthdate = "1987-01-14";
34+
35+
const result = calculateAge(birthdate);
36+
37+
expect(result).toEqual(38);
38+
});
39+
40+
it("should throw if birthdate is invalid", () => {
41+
const birthdate = "1987-13-17";
42+
43+
expect(() => {
44+
calculateAge(birthdate);
45+
}).toThrow();
46+
});
47+
});

src/utils/age.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { UtcDateFromStringSchema } from "@src/utils/date";
2+
import { differenceInYears } from "date-fns";
3+
4+
export const calculateAge = (date: string): number => {
5+
const today: Date = new Date();
6+
const birthDate: Date = UtcDateFromStringSchema.parse(date);
7+
8+
return differenceInYears(today, birthDate);
9+
};

0 commit comments

Comments
 (0)