completefrontend

Predict the outputMedium

Which srcset candidate does this pick?

The tea shop lists its mint tea photo in srcset at four widths. The code turns each width into a density for the slot sizes gives, and applies the HTML Standard's selection rule for three screens: a phone that shows the photo 412 CSS px wide at a device pixel ratio of 2.625, a laptop at 480 px and 2x, and a desktop at 1100 px and 2x. What does it log?

The code
// Leaf and Kettle's photo of mint tea, saved at four widths, as the <img> lists them in srcset.
const srcset = "mint-480.jpg 480w, mint-960.jpg 960w, mint-1440.jpg 1440w, mint-1920.jpg 1920w";
 
// Each candidate's file and width, from its w descriptor.
const candidates = srcset.split(",").map((candidate) => {
  const [url, descriptor] = candidate.trim().split(/\s+/);
  return { url, width: parseInt(descriptor, 10) };
});
 
// The HTML Standard's rule: a candidate's density is its width over the slot. Sort by density, then
// take the first whose density is at least the screen's pixel ratio, or else the densest one.
function pick(slot, devicePixelRatio) {
  const sorted = candidates
    .map(({ url, width }) => ({ url, density: width / slot }))
    .sort((a, b) => a.density - b.density);
  return sorted.find((candidate) => candidate.density >= devicePixelRatio) ?? sorted.at(-1);
}
 
// The slot is how wide sizes says the photo is shown, in CSS pixels.
const screens = [
  { name: "Phone", slot: 412, devicePixelRatio: 2.625 },
  { name: "Laptop", slot: 480, devicePixelRatio: 2 },
  { name: "Desktop", slot: 1100, devicePixelRatio: 2 },
];
 
for (const { name, slot, devicePixelRatio } of screens) {
  const { url, density } = pick(slot, devicePixelRatio);
  console.log(`${name}: ${url} (density ${density.toFixed(2)})`);
}

Practice it in the editor, with tests

The answer

Work out every line it logs, in order. Then check.

Checking your sign-in…