Created
November 27, 2023 21:11
-
-
Save mattkenefick/d84a674fc3c27b5355dbb1af740b2fd3 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
/** | |
* Usage: | |
* | |
* const ratio = approximateAspectRatio(855, 482, 20); | |
* // "16:9" | |
* | |
* @param number width | |
* @param number height | |
* @param number maxRatio | |
* @return string | |
*/ | |
function approximateAspectRatio(width, height, maxRatio = 20) { | |
const targetRatio = width / height; | |
let closestRatio = ''; | |
let closestRatioDifference = Infinity; | |
for (let i = 1; i <= maxRatio; i++) { | |
const j = Math.round(i / targetRatio); | |
const ratio = i / j; | |
const difference = Math.abs(targetRatio - ratio); | |
if (difference < closestRatioDifference) { | |
closestRatioDifference = difference; | |
closestRatio = `${i}:${j}`; | |
} | |
} | |
return closestRatio; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment