Created
October 15, 2017 17:56
-
-
Save KimSarabia/22a684d8a4659bc1a1662deb5a02dc8f to your computer and use it in GitHub Desktop.
Simple fraction to mixed number converter
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
// https://www.codewars.com/kata/simple-fraction-to-mixed-number-converter/ | |
var greatest = (a,b) => (b===0) ? a : greatest(b,a%b) | |
function mixedFraction(s){ | |
arr = s.split('/') | |
dividend = Number(arr[0]) | |
divisor = Number(arr[1]) | |
if(divisor === 0){ | |
throw "ZeroDivisionError"; | |
} else { | |
if(dividend%divisor === 0){ | |
return (dividend/divisor).toString() | |
} else { | |
whole = (dividend/divisor) | 0; | |
numerator = dividend%divisor | |
denominator = Number(divisor) | |
common = greatest(numerator,denominator) | |
fnumerator = numerator/common | |
fdenominator = denominator/common | |
if(Math.abs(dividend) < Math.abs(divisor)){ | |
if(fdenominator < 0){fdenominator = fdenominator * -1; fnumerator = fnumerator * -1} | |
return fnumerator.toString()+'/'+fdenominator.toString() | |
} else { | |
return whole + " " + Math.abs(fnumerator).toString() + "/" + Math.abs(fdenominator).toString() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment