This commit is contained in:
Ruidy 2021-02-19 14:31:13 +01:00
parent afe5a6c7e8
commit 40fd25bfaf
9 changed files with 32 additions and 24 deletions

View file

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

View file

@ -4,5 +4,4 @@
*
@example * `throw new ValidationError("Bad id")`
*/
export class ValidationError extends Error {}

View file

@ -1,6 +1,6 @@
import { assertStrictEquals } from "https://deno.land/std@0.87.0/testing/asserts.ts";
import { sayHello, sayRandomHello } from "./index.ts";
import { ID } from "./types.ts";
import { ID } from "./types/id.ts";
Deno.test("Random Hello", () => {
const result = sayRandomHello();

View file

@ -1,5 +1,5 @@
import { getLocaleById, localesSize } from "./repository/locales.ts";
import { ID } from "./types.ts";
import { ID } from "./types/id.ts";
/**
* Display the iconic Hello, World in a random locale
@ -15,5 +15,5 @@ export const sayRandomHello = () => {
* @param id Unique identifier
*/
export const sayHello = (id: ID): string => {
return getLocaleById(id.id);
return getLocaleById(id.value);
};

View file

@ -1,4 +1,4 @@
import { locales } from "./data.ts";
import { locales } from "./locales.data.ts";
export const localesSize = Object.keys(locales).length;

View file

@ -1,16 +0,0 @@
import { ValidationError } from "./validation.ts";
import { localesSize } from "./repository/locales.ts";
export class ID {
constructor(public id: number) {
this.#isValid(id);
}
#idIsValid = (id: number) => id > 0 && id < localesSize;
#isValid = (id: number) => {
if (!this.#idIsValid(id)) {
throw new ValidationError(`Invalid index: ${id}`);
}
};
}

View file

@ -1,7 +1,7 @@
import { ID } from "./types.ts";
import { ValidationError } from "./validation.ts";
import { assertThrows } from "https://deno.land/std@0.87.0/testing/asserts.ts";
import { localesSize } from "./repository/locales.ts";
import { localesSize } from "../repository/locales.ts";
import { ID } from "./id.ts";
import { ValidationError } from "../errors/exceptions.ts";
Deno.test("ID validation fails for non strictly positive values", () => {
assertThrows(() => new ID(-1), ValidationError, "Invalid index: -1");

20
src/types/id.ts Normal file
View file

@ -0,0 +1,20 @@
import { localesSize } from "../repository/locales.ts";
import { ValidationError } from "../errors/exceptions.ts";
/**
* ID is the input type.
* It validates input value at creation
*/
export class ID {
constructor(public value: number) {
this.#validate(value);
}
#idIsValid = (id: number) => id > 0 && id < localesSize;
#validate = (id: number) => {
if (!this.#idIsValid(id)) {
throw new ValidationError(`Invalid index: ${id}`);
}
};
}