diff --git a/source/index.ts b/source/index.ts index 917034b..8cf77b3 100644 --- a/source/index.ts +++ b/source/index.ts @@ -16,6 +16,12 @@ export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array export interface Ow { (value: T, predicate: Predicate): void; + /** + * Create a reusable validator. + * + * @param predicate Predicate used in the validator function. + */ + create(predicate: Predicate): (value: T) => void; /** * Test the value to be a string. */ @@ -148,6 +154,9 @@ const main = (value: T, predicate: Predicate) => { }; Object.defineProperties(main, { + create: { + value: (predicate: Predicate) => (value: T) => main(value, predicate) + }, string: { get: () => new StringPredicate() }, diff --git a/source/test/test.ts b/source/test/test.ts index 16d7753..894242b 100644 --- a/source/test/test.ts +++ b/source/test/test.ts @@ -7,3 +7,12 @@ test('not', t => { t.notThrows(() => m('foo!', m.string.not.alphanumeric)); 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`'); +});