All files / src/validators helpers.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32                      2x 2x         2x 2x   2x 4x   4x   3x     1x      
import { Validator } from '..';
import { Grammar } from '../utils/grammar';
 
/**
 * A helper validator to coerce strings to numbers before running a subsequent validator
 * @param validator the number validator to execute
 * @returns the reason for the number validator failing
 */
export function coerceNumber(
  validator: Validator.Fn<number | null | undefined>
): Validator.Fn<string | number | null | undefined> {
  return (value: string | number | null | undefined): string | void => {
    return validator(typeof value === 'string' ? Number(value) : value);
  };
}
 
export function or<T>(...validators: Validator.Fn<T>[]): Validator.Fn<T> {
  return (value: T): string | void => {
    const errors: string[] = [];
 
    for (const validator of validators) {
      const response = validator(value);
 
      if (!response) return;
 
      errors.push(response);
    }
 
    return Grammar.and(...errors);
  };
}