All files / src Fraction.ts

100% Statements 24/24
87.5% Branches 7/8
100% Functions 7/7
100% Lines 23/23

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 90  349x 112x     237x 113x   124x             1x                           105x 105x 105x                     1x 29x                         1x 22x                     1x 4x 4x 4x                   1x 113x 113x 113x 113x     1x  
function gcd(a: number, b: number): number {
  if (b > a) {
    return gcd(b, a);
  }
 
  if (b === 0) {
    return a;
  } else {
    return gcd(b, a % b);
  }
}
 
/**
 * A fraction with a numerator and a denominator.
 */
export class Fraction {
  private _numerator: number;
  private _denominator: number;
 
  /**
   * Creates and immediately reduce the fraction using the greatest common
   * divider of the numerator and denominator.
   *
   * @param {number} numerator
   *   The numerator of this fraction.
   * @param {number} denominator
   *   The denominator of this fraction.
   */
  constructor(numerator: number, denominator: number) {
    this._numerator = numerator;
    this._denominator = denominator;
    this._reduce();
  }
 
  /**
   * Return a new fraction by adding the given fraction to this fraction.
   *
   * @param {Fraction} other
   *   The fraction to add to this one.
   * @return {Fraction}
   *   A new fraction obtained by adding the 2 fractions.
   */
  public add(other: Fraction): Fraction {
    return new Fraction(
      this._numerator * other._denominator +
        other._numerator * this._denominator,
      this._denominator * other._denominator
    );
  }
 
  /**
   * Returns the number value of this fraction.
   *
   * @return {number}
   *   The number value of this fraction
   */
  public valueOf(): number {
    return this._numerator / this._denominator;
  }
 
  /**
   * Checks if this fraction is equal to the provided fraction.
   *
   * @param {Fraction} other
   *   The fraction to compare to.
   * @return {boolean}
   *   `true` if the 2 fractions are equal, `false` else.
   */
  public sameAs(other: Fraction): boolean {
    this._reduce();
    other._reduce();
    return (
      this._numerator === other._numerator &&
      this._denominator === other._denominator
    );
  }
 
  /**
   * Reduce the fraction using the greatest common divider of the numerator
   * and the denominator.
   */
  private _reduce(): void {
    const div = gcd(this._numerator, this._denominator);
    Eif (div) {
      this._numerator = this._numerator / div;
      this._denominator = this._denominator / div;
    }
  }
}