Skip to content

Instantly share code, notes, and snippets.

@fhefh2015
Forked from otakustay/index.js
Created March 11, 2021 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhefh2015/f1b733443077d533faa284bfbd9cb46e to your computer and use it in GitHub Desktop.
Save fhefh2015/f1b733443077d533faa284bfbd9cb46e 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