Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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