diff --git a/src/exercises/TP1/AgeValidation/index.test.ts b/src/exercises/TP1/AgeValidation/index.test.ts new file mode 100644 index 0000000..e07acbb --- /dev/null +++ b/src/exercises/TP1/AgeValidation/index.test.ts @@ -0,0 +1,29 @@ +import { AgeValidation } from "./index"; + +describe("Test AgeValidation", () => { + const ageValidator = new AgeValidation(); + + it.each([ + { input: "30", expected: 30 }, + { input: "25", expected: 25 }, + { input: "50", expected: 50 }, + ])( + "should validate age %s correctly", + ({ input, expected }) => { + const result = ageValidator.validateAge(input); + expect(result).toEqual(expected); + console.log(`Test with input = ${input}, expected = ${expected}, result = ${result}`); + } + ); + + it.each([ + { input: "17", expectedErrorMsg: "L'âge doit être compris entre 18 et 130 ans" }, + { input: "131", expectedErrorMsg: "L'âge doit être compris entre 18 et 130 ans" }, + { input: "abc", expectedErrorMsg: "L'âge doit représenter un nombre entier positif" }, + ])( + "should throw a validation exception for invalid age %s", + ({ input, expectedErrorMsg }) => { + expect(() => ageValidator.validateAdult(input)).toThrowError(expectedErrorMsg); + } + ); +}); diff --git a/src/exercises/TP1/AgeValidation/index.ts b/src/exercises/TP1/AgeValidation/index.ts new file mode 100644 index 0000000..16c2eba --- /dev/null +++ b/src/exercises/TP1/AgeValidation/index.ts @@ -0,0 +1,40 @@ +export class AgeValidation { + validateAge(input: string): number { + try { + const age = this.validateNumber(input); + if (!Number.isInteger(age) || age < 0) { + throw new ValidationException("L'âge doit représenter un nombre entier positif"); + } + return age; + } catch (error) { + if (error instanceof ValidationException) { + throw new ValidationException("L'âge doit représenter un nombre entier positif"); + } else { + throw error; + } + } + } + + validateAdult(input: string): number { + const age = this.validateAge(input); + if (age < 18 || age > 130) { + throw new ValidationException("L'âge doit être compris entre 18 et 130 ans"); + } + return age; + } + + private validateNumber(input: string): number { + const num = parseFloat(input); + if (isNaN(num)) { + throw new ValidationException('La valeur doit représenter un nombre'); + } + return num; + } +} + +export class ValidationException extends Error { + constructor(message: string) { + super(message); + this.name = 'ValidationException'; + } +}