added number

This commit is contained in:
Sebastian Seedorf
2020-05-26 00:42:16 +02:00
parent 218e596ede
commit c59e4a6a50
5 changed files with 101 additions and 4 deletions

69
validators/number.test.ts Normal file
View File

@@ -0,0 +1,69 @@
import { isNumber, isInteger } from "./number.ts";
import { validate } from "../mod.ts";
import {
assertEquals,
assertNotEquals,
} from "https://deno.land/std@0.53.0/testing/asserts.ts";
Deno.test("isNumber (match)", async () => {
const values = [
0,
1,
2e64,
-1,
0.1,
Math.PI,
];
for (const value of values) {
assertEquals(await validate(value, isNumber), []);
}
});
Deno.test("isNumber (no match)", async () => {
const values = [
undefined,
null,
NaN,
"0",
true,
false,
() => {},
function named() {},
new Object(),
Symbol(),
];
for (const value of values) {
assertNotEquals(await validate(value, isNumber), []);
}
});
Deno.test("isInteger (match)", async () => {
const values = [
0,
1,
2e64,
-1,
];
for (const value of values) {
assertEquals(await validate(value, isInteger), []);
}
});
Deno.test("isInteger (no match)", async () => {
const values = [
undefined,
null,
NaN,
"0",
true,
false,
() => {},
function named() {},
new Object(),
Symbol(),
0.1,
];
for (const value of values) {
assertNotEquals(await validate(value, isInteger), []);
}
});

25
validators/number.ts Normal file
View File

@@ -0,0 +1,25 @@
import { Validator, Args } from "../mod.ts";
export const isNumber: Validator = {
type: "isNumber",
check: (value: any) => {
if (!Number.isFinite(value)) {
return {};
}
},
message: (value: any, args?: Args) => {
return `The value '${value && value.toString()}' has to be a number.`;
},
};
export const isInteger: Validator = {
type: "isInteger",
check: (value: any) => {
if (!Number.isInteger(value)) {
return {};
}
},
message: (value: any, args?: Args) => {
return `The value '${value && value.toString()}' has to be an integer.`;
},
};

View File

@@ -13,7 +13,7 @@ Deno.test("isString (match)", async () => {
new String("bar"),
];
for (const value of values) {
assertEquals([], await validate(value, isString));
assertEquals(await validate(value, isString), []);
}
});
@@ -31,6 +31,6 @@ Deno.test("isString (no match)", async () => {
Symbol(),
];
for (const value of values) {
assertNotEquals([], await validate(value, isString));
assertNotEquals(await validate(value, isString), []);
}
});