age
This commit is contained in:
parent
b47e3608b5
commit
e61ce661f5
29
src/exercises/TP1/AgeValidation/index.test.ts
Normal file
29
src/exercises/TP1/AgeValidation/index.test.ts
Normal file
@ -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);
|
||||
}
|
||||
);
|
||||
});
|
40
src/exercises/TP1/AgeValidation/index.ts
Normal file
40
src/exercises/TP1/AgeValidation/index.ts
Normal file
@ -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';
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user