mirror of https://github.com/lukechilds/ow.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
949 B
50 lines
949 B
import * as is from '@sindresorhus/is';
|
|
import {not} from '../operators/not';
|
|
|
|
export interface Validator<T> {
|
|
message(value: T): string;
|
|
validator(value: T): boolean;
|
|
}
|
|
|
|
export interface Context {
|
|
validators: Validator<any>[];
|
|
}
|
|
|
|
export const validatorSymbol = Symbol('validators');
|
|
|
|
export abstract class Predicate<T = any> {
|
|
constructor(
|
|
type: string,
|
|
private context: Context = {
|
|
validators: []
|
|
}
|
|
) {
|
|
this.addValidator({
|
|
message: value => `Expected argument to be of type \`${type}\` but received type \`${is(value)}\``,
|
|
validator: value => is[type](value)
|
|
});
|
|
}
|
|
|
|
get [validatorSymbol]() {
|
|
return this.context.validators;
|
|
}
|
|
|
|
/**
|
|
* Invert the following validators.
|
|
*/
|
|
get not() {
|
|
return not(this);
|
|
}
|
|
|
|
/**
|
|
* Register a new validator.
|
|
*
|
|
* @internal
|
|
* @param validator Validator to register.
|
|
*/
|
|
addValidator(validator: Validator<T>) {
|
|
this.context.validators.push(validator);
|
|
|
|
return this;
|
|
}
|
|
}
|
|
|