46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
|
|
//#region src/core/validator.ts
|
||
|
|
const string = (value) => typeof value === "string";
|
||
|
|
const number = (value) => typeof value === "number";
|
||
|
|
const boolean = (value) => typeof value === "boolean";
|
||
|
|
const bigint = (value) => typeof value === "bigint";
|
||
|
|
/** Matches an instance of the given constructor. */
|
||
|
|
function instanceOf(ctor) {
|
||
|
|
return (value) => value instanceof ctor;
|
||
|
|
}
|
||
|
|
/** Matches when any of the given validators match. */
|
||
|
|
function union(...validators) {
|
||
|
|
return (value) => {
|
||
|
|
for (let i = 0, len = validators.length; i < len; i++) if (validators[i](value)) return true;
|
||
|
|
return false;
|
||
|
|
};
|
||
|
|
}
|
||
|
|
/** Matches the given validator or `undefined`. */
|
||
|
|
function optional(validator) {
|
||
|
|
return (value) => value === void 0 || validator(value);
|
||
|
|
}
|
||
|
|
/** Matches an array whose items each match `item`. */
|
||
|
|
function array(item) {
|
||
|
|
return (value) => {
|
||
|
|
if (!Array.isArray(value)) return false;
|
||
|
|
for (let i = 0, len = value.length; i < len; i++) if (!item(value[i])) return false;
|
||
|
|
return true;
|
||
|
|
};
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Matches an object whose declared keys each pass their validator. Extra keys
|
||
|
|
* are not checked.
|
||
|
|
*/
|
||
|
|
function object(shape) {
|
||
|
|
const keys = Object.keys(shape);
|
||
|
|
return (value) => {
|
||
|
|
if (value == null || typeof value !== "object") return false;
|
||
|
|
for (let i = 0, len = keys.length; i < len; i++) {
|
||
|
|
const key = keys[i];
|
||
|
|
if (!shape[key](Reflect.get(value, key))) return false;
|
||
|
|
}
|
||
|
|
return true;
|
||
|
|
};
|
||
|
|
}
|
||
|
|
//#endregion
|
||
|
|
export { array, bigint, boolean, instanceOf, number, object, optional, string, union };
|