All files / validation arrayValidation.ts

100% Statements 49/49
100% Branches 14/14
100% Functions 3/3
100% Lines 49/49

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x 1x 1x 1x 1x 33x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 15x 5x 5x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 4x 4x 3x 3x 3x 1x 1x 1x 1x 4x 2x 2x 2x  
import { makeArrayOrDefault } from '@helpers/arrayHelper';
import { ValidationResult } from '@contracts/validationResult';
 
export const minItems =
  (minLength: number) =>
  <T>(values: Array<T>): ValidationResult => {
    const safeArr = makeArrayOrDefault(values);
    if (safeArr.length >= minLength) {
      return { isValid: true };
    }
 
    return {
      isValid: false,
      errorMessage: `Minimum number of items that need to be selected is ${minLength}`,
    };
  };
 
export const maxItems =
  (maxLength: number) =>
  <T>(values: Array<T>): ValidationResult => {
    const safeArr = makeArrayOrDefault(values);
    if (safeArr.length <= maxLength) {
      return { isValid: true };
    }
 
    return {
      isValid: false,
      errorMessage: `Too many items selected! Maximum number of items allowed to be selected is ${maxLength}`,
    };
  };
 
export const selectedItemsExist =
  <T>(validOptions: Array<T>) =>
  (values: Array<T>): ValidationResult => {
    const safeArr = makeArrayOrDefault(values);
    for (const value of safeArr) {
      let optionIsValid = false;
      if (validOptions.includes(value)) {
        optionIsValid = true;
        continue;
      }
 
      if (optionIsValid == false) {
        return { isValid: false, errorMessage: 'Selected option is invalid' };
      }
    }
 
    return { isValid: true };
  };