Created
May 7, 2014 00:49
-
-
Save calebsander/7d7f086979682b9c11a9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function Fraction(n, d) { | |
this.n = n; | |
if (d) this.d = d; | |
else this.d = 1; | |
} | |
Fraction.prototype.reciprocal = function() { | |
return {n: this.d, d: this.n}; | |
} | |
function gcf(x, y) { | |
if (y > x) { | |
return gcf(y, x); | |
} | |
if (!y) { | |
return x; | |
} | |
var r = x % y; | |
return gcf(y, r); | |
} | |
Fraction.prototype.reduce = function() { | |
if (!this.d || this.n % 1 || this.d % 1) return {success: false, error: 'invalid fraction'}; | |
var that = new Fraction(this.n, this.d); | |
if (that.d < 0) { | |
that.n *= -1; | |
that.d *= -1; | |
} | |
var factor = 2; | |
while (gcf(Math.abs(that.n), Math.abs(that.d)) != 1) { | |
if (!(Math.abs(that.n) % factor) && !(Math.abs(that.d) % factor)) { | |
that.n /= factor; | |
that.d /= factor; | |
} | |
else factor++; | |
} | |
return that; | |
} | |
Fraction.prototype.add = function(frac2) { | |
var that = new Fraction(this.n, this.d).reduce(); | |
frac2 = frac2.reduce(); | |
return new Fraction(that.n * frac2.d + frac2.n * that.d, that.d * frac2.d).reduce(); | |
} | |
Fraction.prototype.subtract = function(frac2) { | |
var that = new Fraction(this.n, this.d).reduce(); | |
frac2 = frac2.reduce(); | |
frac2.n *= -1; | |
return new Fraction(that.n * frac2.d + frac2.n * that.d, that.d * frac2.d).reduce(); | |
} | |
Fraction.prototype.gt = function(frac2) { | |
return this.n * frac2.d > this.d * frac2.n; | |
} | |
Fraction.prototype.lt = function(frac2) { | |
return this.n * frac2.d < this.d * frac2.n; | |
} | |
Fraction.prototype.equals = function(frac2) { | |
return this.n * frac2.d == this.d * frac2.n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment