Browse Source

Add `not` predicate (#12)

iss58
Sam Verschueren 7 years ago
committed by Sindre Sorhus
parent
commit
494cc40994
  1. 22
      source/lib/operators/not.ts
  2. 9
      source/lib/predicates/predicate.ts
  3. 9
      source/test/test.ts

22
source/lib/operators/not.ts

@ -0,0 +1,22 @@
import { Predicate, Validator, validatorSymbol } from '../predicates/predicate';
/**
* Operator which inverts all the validations.
*
* @param predictate Predicate to wrap inside the operator.
*/
export const not = <T extends Predicate>(predicate: T) => {
predicate['addValidator'] = (validator: Validator<any>) => { // tslint:disable-line:no-string-literal
const fn = validator.validator;
const message = validator.message;
validator.message = (x: any) => `[NOT] ${message(x)}`;
validator.validator = (x: any) => !fn(x);
predicate[validatorSymbol].push(validator);
return predicate;
};
return predicate;
};

9
source/lib/predicates/predicate.ts

@ -1,4 +1,5 @@
import * as is from '@sindresorhus/is'; import * as is from '@sindresorhus/is';
import { not } from '../operators/not';
export interface Validator<T> { export interface Validator<T> {
message(value: T): string; message(value: T): string;
@ -12,6 +13,7 @@ export interface Context {
export const validatorSymbol = Symbol('validators'); export const validatorSymbol = Symbol('validators');
export abstract class Predicate<T = any> { export abstract class Predicate<T = any> {
constructor( constructor(
type: string, type: string,
private context: Context = { validators: [] } private context: Context = { validators: [] }
@ -26,6 +28,13 @@ export abstract class Predicate<T = any> {
return this.context.validators; return this.context.validators;
} }
/**
* Invert the following validators.
*/
get not() {
return not(this);
}
/** /**
* Register a new validator. * Register a new validator.
* *

9
source/test/test.ts

@ -0,0 +1,9 @@
import test from 'ava';
import * as m from '..';
test('not', t => {
t.notThrows(() => m(1, m.number.not.infinite));
t.notThrows(() => m(1, m.number.not.infinite.greaterThan(5)));
t.notThrows(() => m('foo!', m.string.not.alphanumeric));
t.throws(() => m('', m.string.not.empty), '[NOT] Expected string to be empty, got ``');
});
Loading…
Cancel
Save