SHARE
TWEET

Rational.mjs

a guest Jun 20th, 2019 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
  2.  
  3. export default class Rational {
  4.   constructor(a = 0, b = 1) {
  5.     if (b < 0) return new Rational(-a, -b);
  6.     const g = gcd(a, b);
  7.     this.numerator = a / g;
  8.     this.denominator = b / g;
  9.   }
  10.  
  11.   add(that) {
  12.     if (!(that instanceof Rational)) return this.add(new Rational(that));
  13.     const a = this.numerator;
  14.     const b = this.denominator;
  15.     const c = that.numerator;
  16.     const d = that.denominator;
  17.     return new Rational(a * d - b * c, b * d);
  18.   }
  19.  
  20.   sub(that) {
  21.     if (!(that instanceof Rational)) return this.sub(new Rational(that));
  22.     return this.add(that.mul(-1));
  23.   }
  24.  
  25.   mul(that) {
  26.     if (!(that instanceof Rational)) return this.mul(new Rational(that));
  27.     const a = this.numerator;
  28.     const b = this.denominator;
  29.     const c = that.numerator;
  30.     const d = that.denominator;
  31.     return new Rational(a * c, b * d);
  32.   }
  33.  
  34.   div(that) {
  35.     if (!(that instanceof Rational)) return this.div(new Rational(that));
  36.     return this.mul(that.pow(-1));
  37.   }
  38.  
  39.   sqrt() {
  40.     return this.pow(1 / 2);
  41.   }
  42.  
  43.   pow(that) {
  44.     const a = this.numerator;
  45.     const b = this.denominator;
  46.     return new Rational(a**that, b**that);
  47.   }
  48.  
  49.   equals(that) {
  50.     if (!(that instanceof Rational)) return this.equals(new Rational(that));
  51.     const a = this.numerator;
  52.     const b = this.denominator;
  53.     const c = that.numerator;
  54.     const d = that.denominator;
  55.     return a * d === b * c;
  56.   }
  57.  
  58.   valueOf() {
  59.     const a = this.numerator;
  60.     const b = this.denominator;
  61.     return a / b;
  62.   }
  63.  
  64.   toString() {
  65.     const a = this.numerator;
  66.     const b = this.denominator;
  67.     return b === 1 ? `${a}` : `${a}/${b}`;
  68.   }
  69. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top