All files / src/auxiliary Predicate.ts

100% Statements 21/21
100% Branches 8/8
100% Functions 5/5
100% Lines 21/21

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89              29x 29x 29x                                               29x 43x                   29x 23x 1x 22x 4x   2x 2x       18x                           29x 4x 1x 3x 2x   1x                     29x 2x  
/**
 * Predicate.ts
 * 
 * Candidate for inclusion in api-ts
 * Defines a Predicate type that can test values of type T.
 */
 
import { guardFunctions, OptionalType, RequiredType } from "@jonloucks/contracts-ts/api/Types";
import { presentCheck } from "@jonloucks/contracts-ts/auxiliary/Checks";
import { used } from "./Checks";
 
/** 
 * A method that tests a value of type T and returns a boolean
 */
export type Method<T> = (value: T) => boolean;
 
/** 
 * A Predicate that tests values of type T
 */
export interface Predicate<T> { test(value: T): boolean; }
 
/** 
 * A type that can be a Method, Predicate, or a boolean
 */
export type Type<T> = Method<T> | Predicate<T> | boolean;
 
/**
 * Duck type guard check for Predicate
 * 
 * @param instance the instance to check
 * @param <T> the type of value tested
 * @returns true if instance is a Predicate, false otherwise
 */
export function guard<T>(instance: unknown): instance is Predicate<T> {
  return guardFunctions(instance, 'test');
}
 
/**
 * Convert a Type to a Predicate
 * 
 * @param type the type to convert
 * @param <T> the type of value tested
 * @returns a Predicate that tests values of type T
 */
export function fromType<T>(type: Type<T>): Predicate<T> {
  if (guard(type)) {
    return type;
  } else if (typeof type === 'boolean') {
    return {
      test: (value: T) : boolean => {
        used(value);
        return type;
      }
    };
  } else {
    return {
      test: type
    };
  }
}
 
/**
 * Test a value against a Predicate Type
 * 
 * @param type the Predicate Type
 * @param value the value to test
 * @param <T> the type of value tested
 * @returns true if the value satisfies the Predicate, false otherwise
 */
export function toValue<T>(type: Type<T>, value: T): boolean {
  if (guard(type)) {
    return type.test(value);
  } else if (typeof type === 'boolean') {
    return type;
  } else {
    return type(value);
  }
}
 
/**
 * Check that a predicate is present
 *
 * @param predicate the predicate to check
 * @return the predicate if present
 * @throws IllegalArgumentException if the predicate is not present
 */
export function check<T>(predicate: OptionalType<Predicate<T>>): RequiredType<Predicate<T>> {
  return presentCheck(predicate, "Predicate must be Present.");
}