Skip to content

Instantly share code, notes, and snippets.

@otakustay
Created March 10, 2021 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save otakustay/37d28c2003a6b8e9a4179a8d662463df to your computer and use it in GitHub Desktop.
Save otakustay/37d28c2003a6b8e9a4179a8d662463df to your computer and use it in GitHub Desktop.
Compute aspect ratio
const isApproximateInteger = value => {
const min = Math.floor(value);
const max = Math.ceil(value);
return value - min <= 0.01 || max - value <= 0.01;
};
const MAX_TRY = 120;
const computeToRatio = (width, height) => {
const base = width / height;
for (let i = 1; i <= MAX_TRY; i++) {
const value = base * i;
if (isApproximateInteger(value)) {
console.log(`${Math.round(value)} : ${i}`);
return;
}
}
console.log(`${width} : ${height}`);
};
computeToRatio(1920, 1080); // 16 : 9
computeToRatio(982, 737); // 4 : 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment