Browse Source

Add reusable validators - fixes #41 (#42)

iss58
Sam Verschueren 7 years ago
committed by Sindre Sorhus
parent
commit
f64f1cd022
  1. 9
      source/index.ts
  2. 9
      source/test/test.ts

9
source/index.ts

@ -16,6 +16,12 @@ export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array
export interface Ow { export interface Ow {
<T>(value: T, predicate: Predicate<T>): void; <T>(value: T, predicate: Predicate<T>): void;
/**
* Create a reusable validator.
*
* @param predicate Predicate used in the validator function.
*/
create<T>(predicate: Predicate<T>): (value: T) => void;
/** /**
* Test the value to be a string. * Test the value to be a string.
*/ */
@ -148,6 +154,9 @@ const main = <T>(value: T, predicate: Predicate<T>) => {
}; };
Object.defineProperties(main, { Object.defineProperties(main, {
create: {
value: <T>(predicate: Predicate<T>) => (value: T) => main(value, predicate)
},
string: { string: {
get: () => new StringPredicate() get: () => new StringPredicate()
}, },

9
source/test/test.ts

@ -7,3 +7,12 @@ test('not', t => {
t.notThrows(() => m('foo!', m.string.not.alphanumeric)); t.notThrows(() => m('foo!', m.string.not.alphanumeric));
t.throws(() => m('' as any, m.string.not.empty), '[NOT] Expected string to be empty, got ``'); t.throws(() => m('' as any, m.string.not.empty), '[NOT] Expected string to be empty, got ``');
}); });
test('reusable validator', t => {
const checkUsername = m.create(m.string.minLength(3));
t.notThrows(() => checkUsername('foo'));
t.notThrows(() => checkUsername('foobar'));
t.throws(() => checkUsername('fo'), 'Expected string to have a minimum length of `3`, got `fo`');
t.throws(() => checkUsername(5 as any), 'Expected argument to be of type `string` but received type `number`');
});

Loading…
Cancel
Save