-
-
Save parzibyte/e8c1800a693f61c87e06fc1a77c4ad41 to your computer and use it in GitHub Desktop.
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 Fraccion { | |
/* | |
https://parzibyte.me/blog | |
*/ | |
constructor(numerador, denominador) { | |
this.setNumerador(numerador); | |
this.setDenominador(denominador); | |
} | |
setNumerador(numerador) { | |
this.numerador = numerador; | |
} | |
setDenominador(denominador) { | |
if (denominador === 0) { | |
throw "El denominador debe ser distinto de 0"; | |
} | |
this.denominador = denominador; | |
} | |
// Ayudantes | |
maximoComunDivisor(a, b) { | |
let temporal;//Para no perder b | |
while (b != 0) { | |
temporal = b; | |
b = a % b; | |
a = temporal; | |
} | |
return a; | |
} | |
minimoComunMultiplo(a, b) { | |
return (a * b) / this.maximoComunDivisor(a, b); | |
} | |
// Operaciones | |
suma(otra) { | |
const mcm = this.minimoComunMultiplo(this.denominador, otra.denominador); | |
const diferenciaFraccionActual = mcm / this.denominador; | |
const diferenciaOtraFraccion = mcm / otra.denominador; | |
const resultado = new Fraccion(); | |
resultado.setNumerador( | |
(diferenciaFraccionActual * this.numerador) + (diferenciaOtraFraccion * otra.numerador)); | |
resultado.setDenominador(mcm); | |
return resultado; | |
} | |
resta(otra) { | |
const mcm = this.minimoComunMultiplo(this.denominador, otra.denominador); | |
const diferenciaFraccionActual = mcm / this.denominador; | |
const diferenciaOtraFraccion = mcm / otra.denominador; | |
const resultado = new Fraccion(); | |
resultado.setNumerador( | |
(diferenciaFraccionActual * this.numerador) - (diferenciaOtraFraccion * otra.numerador)); | |
resultado.setDenominador(mcm); | |
return resultado; | |
} | |
producto(otra) { | |
return new Fraccion(this.numerador * otra.numerador, this.denominador * otra.denominador); | |
} | |
cociente(otra) { | |
return new Fraccion(this.numerador * otra.denominador, this.denominador * otra.numerador); | |
} | |
inversa() { | |
return new Fraccion(this.denominador, this.numerador); | |
} | |
potencia(exponente) { | |
return new Fraccion(Math.pow(this.numerador, exponente), Math.pow(this.denominador, exponente)); | |
} | |
simplifica() { | |
const mcd = this.maximoComunDivisor(this.numerador, this.denominador); | |
return new Fraccion(this.numerador / mcd, this.denominador / mcd); | |
} | |
aMixta() { | |
return FraccionMixta.desdeImpropia(this); | |
} | |
toString() { | |
return `${this.numerador}/${this.denominador}`; | |
} | |
equals(otra) { | |
return this.numerador === otra.numerador && this.denominador === otra.denominador; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment