All files / src/app/core/models/price price.helper.ts

100% Statements 25/25
100% Branches 14/14
100% Functions 7/7
100% Lines 25/25

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        34x   18x 13x                           7x 7x 1x   6x           15x 10x               29x 24x               15x               3x 1x   2x 1x   1x       62x 6x   56x 3x   53x 3x   50x 3x        
import { PriceItem } from 'ish-core/models/price-item/price-item.model';
 
import { Price } from './price.model';
 
export class PriceHelper {
  static diff(p1: Price, p2: Price): Price {
    PriceHelper.sanityChecks(p1, p2);
    return {
      type: p1.type,
      currency: p1.currency,
      value: Math.round((p1.value - p2.value) * 100) / 100,
    };
  }
 
  /**
   * Inverts the value of a price
   *
   * @param price The price
   * @returns inverted price
   */
  static invert<T extends Price | PriceItem>(price: T): T {
    if (price) {
      if (price.type === 'Money') {
        return { ...price, value: (price as Price).value * -1 };
      }
      return { ...price, gross: (price as PriceItem).gross * -1, net: (price as PriceItem).net * -1 };
    }
  }
 
  // visible-for-testing
  static min(p1: Price, p2: Price): Price {
    PriceHelper.sanityChecks(p1, p2);
    return {
      type: p1.type,
      currency: p1.currency,
      value: Math.round(Math.min(p1.value, p2.value) * 100) / 100,
    };
  }
 
  static sum(p1: Price, p2: Price): Price {
    PriceHelper.sanityChecks(p1, p2);
    return {
      type: p1.type,
      currency: p1.currency,
      value: Math.round((p1.value + p2.value) * 100) / 100,
    };
  }
 
  static empty(currency?: string): Price {
    return {
      type: 'Money',
      value: 0,
      currency,
    };
  }
 
  static getPrice(currency: string, value: number): Price {
    if (!currency) {
      throw new Error('getPrice cannot handle undefined currency');
    }
    if (value === undefined) {
      throw new Error('getPrice cannot handle undefined value');
    }
    return { currency, value, type: 'Money' };
  }
 
  private static sanityChecks(p1: Price, p2: Price) {
    if (!p1 || !p2) {
      throw new Error('cannot handle undefined inputs');
    }
    if (!Number.isFinite(p1.value) || !Number.isFinite(p2.value)) {
      throw new Error('cannot handle undefined values');
    }
    if (!p1.currency || !p2.currency) {
      throw new Error('cannot handle undefined currency');
    }
    if (p1.currency !== p2.currency) {
      throw new Error('currency mismatch');
    }
  }
}