All files / src/impl ExtractorPromisor.impl.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 6/6
100% Lines 15/15

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 6425x   25x                     25x 3x                               4x 4x 1x   3x               3x             3x       3x       3x 3x     3x 3x  
import { presentCheck, promisorCheck } from "@jonloucks/contracts-ts/auxiliary/Checks";
import { Promisor } from "@jonloucks/contracts-ts/api/Promisor";
import { isNotPresent, OptionalType, RequiredType, Transform } from "@jonloucks/contracts-ts/api/Types";
 
/**
 * Factory method to create an ExtractPromisorImpl which is extraction promisor
 * 
 * @param referent the source promisor
 * @param transform the transform function to extract the new value
 * @param <T> the input deliverable type
 * @param <R> the output deliverable type           
 * @returns the new Extract Promisor implementation
 */
export function create<T, R>(referent: Promisor<T>, transform: Transform<T, R>): RequiredType<Promisor<R>> {
  return ExtractorPromisorImpl.internalCreate<T, R>(referent, transform);
}
 
// ---- Implementation details below ----
 
/**
 * Implementation of an Extractor Promisor
 * @param <T> the input deliverable type
 * @param <R> the output deliverable type
 */
class ExtractorPromisorImpl<T, R> implements Promisor<R> {
 
  /**
   * Promisor.demand override.
   */
  demand(): OptionalType<R> {
    const referentValue = this.#referent.demand();
    if (isNotPresent(referentValue)) {
      return referentValue;
    } else {
      return this.#transform.transform(referentValue);
    }
  }
 
  /**
   * Promisor.incrementUsage override.
   */
  incrementUsage(): number {
    return this.#referent.incrementUsage();
  }
 
  /**
   * Promisor.decrementUsage override.
   */
  decrementUsage(): number {
    return this.#referent.decrementUsage();
  }
 
  static internalCreate<T, R>(referent: Promisor<T>, transform: Transform<T, R>): RequiredType<Promisor<R>> {
    return new ExtractorPromisorImpl<T, R>(referent, transform);
  }
 
  private constructor(referent: Promisor<T>, transform: Transform<T, R>) {
    this.#referent = promisorCheck(referent);
    this.#transform = presentCheck(transform, "Transform must be present.");
  }
 
  readonly #referent: Promisor<T>;
  readonly #transform: Transform<T, R>;
}