Created
June 8, 2017 23:29
-
-
Save gitexec/3ec524e7f9c8098f3c90663d5dd7266f to your computer and use it in GitHub Desktop.
Class definition with methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fraction{ | |
constructor(top, bottom){ | |
this.num = top; | |
this.den = bottom; | |
} | |
show() { | |
console.log('${this.num}/${this.den}'); | |
} | |
gcd(m = this.num, n = this.den){ | |
while((m%n) != 0){ | |
let oldm = m; | |
let oldn = n; | |
m = n; | |
n = oldm%oldn; | |
} | |
return n; | |
} | |
plus(fraction){ | |
let newnum = this.num * fraction.den + this.den * fraction.num; | |
let newden = this.den * fraction.den; | |
let common = this.gcd(newnum,newden); | |
return new Fraction(Math.trunc(newnum/common),Math.trunc(newden/common)); | |
} | |
equal(fraction) { | |
let firstNum = this.num * fraction.den; | |
let seconNum = fraction.num * this.den; | |
return firstNum == seconNum; | |
} | |
} | |
var f1 = new Fraction(2,3); | |
console.log(f1.num); | |
var f2 = new Fraction(2,3); | |
console.log(f1.equal(f2)); | |
console.log(f1.plus(f2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment