3 ms·
I mean, you can come up with a silly example like `sum`, but here's a more real-world example (takes the width and height of a container, and calculates a scali
by mhink 5y ago
I mean, you can come up with a silly example like `sum`, but here's a more real-world example (takes the width and height of a container, and calculates a scaling factor and translation which make an element fit inside the container at a target aspect ratio).
const containerRatio = (containerWidth / containerHeight);
const targetRatio = (targetWidth / targetHeight);
const useVertical = (containerRatio > targetRatio);
const scaleFactor = (isVertical
? (containerHeight / targetHeight)
: (containerWidth / targetWidth)
);
const scaledWidth = targetWidth * scaleFactor;
const scaledHeight = targetHeight * scaleFactor;
let x0 = 0;
if (isVertical) {
x0 = 0.5 * (containerWidth - scaledWidth);
x0 /= (1 - scaleFactor);
}
let y0 = 0;
if (!isVertical) {
y0 = 0.5 * (containerHeight - scaledHeight);
y0 /= (1 - scaleFactor);
}
return [[x0, y0], scalingFactor];
You could also write this as:
const r = (w / h);
const tr = (tw / th);
const m = (r > tr ? (h / th) : (w / tw));
const o = [0, 0];
if (r > tr) {
o[0] = (0.5 * (w - tw * m)) / (1 - m);
} else {
o[1] = (0.5 * (h - th * m)) / (1 - m);
}
return [o, m];
It's certainly terser (and I could have made it terser still), but the first example scans better IMO, because it breaks the expression evaluation down into steps which explain what the calculation is doing.
If there was a problem with the second example, I'd have to more or less rewrite the logic myself into the first form in order to figure out what it was doing.