Created
March 15, 2020 23:17
-
-
Save dysfunc/905b8f48f37b5339854b5242db73e4e3 to your computer and use it in GitHub Desktop.
Determine the aspect ratio of something
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
/** | |
* Finds the greatest common divisor (GCD) by determining the highest | |
* number that evenly divides both numbers | |
* @param {Number} width Width of the object | |
* @param {Number} height Height of the object | |
* @return {Number} GCD number | |
*/ | |
const gcd = (width, height) => height === 0 ? width : gcd(height, width % height); | |
/** | |
* Returns the closest aspect ratio from the passed width and height. | |
* Takes the GCD and divides both values by that. | |
* @param {Number} width Width of the object | |
* @param {Number} height Height of the object | |
* @return {String} The closest matching aspect ratio | |
* | |
* For example: | |
* 1024x768 monitor has a GCD of 256. | |
* When you divide both values by 256 you get 4x3 or 4:3. | |
*/ | |
const getAspectRatio = (width, height) => { | |
const ratio = gcd(width, height); | |
return `${width/ratio}:${height/ratio}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment