Created
January 29, 2015 15:51
-
-
Save Langmans/840149d3da0eecdccbea 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
var textualRatio = (function () { | |
var | |
isInteger, | |
greatestCommonDivisor; | |
/** | |
* | |
* @param value | |
* @returns {boolean} | |
*/ | |
isInteger = function (value) { | |
return !!/^[0-9]+$/.test(value); | |
}; | |
/** | |
* | |
* Greatest Common Divisor | |
* @param {number} a | |
* @param {number} b | |
* @returns {number} | |
*/ | |
greatestCommonDivisor = function (a, b) { | |
if (b === 0) return a; | |
return greatestCommonDivisor(b, a % b); | |
}; | |
/** | |
* Reduce a numerator and denominator to it's smallest, integer ratio using Euclid's Algorithm | |
* @param {number|string} numerator | |
* @param {number|string} denominator | |
* @returns {string} | |
*/ | |
return function (numerator, denominator) { | |
var divisor, temp; | |
if (!isInteger(numerator) || !isInteger(denominator)) { | |
return '?:?'; | |
} | |
else if (numerator === denominator) { | |
return '1:1'; | |
} | |
else if (+numerator < +denominator) { | |
temp = numerator; | |
numerator = denominator; | |
denominator = temp; | |
} | |
divisor = greatestCommonDivisor(+numerator, +denominator); | |
return 'undefined' === typeof temp | |
? (numerator / divisor) + ':' + (denominator / divisor) | |
: (denominator / divisor) + ':' + (numerator / divisor); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment