completefrontend

Write the codeMedium

Write a function that picks a fallback font's size-adjust and overrides.

The tea shop's recipes are in Caveat, and until it loads they show in a local font. So that the swap doesn't move the page, the build writes a fallback @font-face for each local font, and needs its numbers. Write fallbackOverrides(webFont, fallbackFont), which returns { sizeAdjust, ascentOverride, descentOverride, lineGapOverride }, each a percentage rounded to two decimal places, as a number: 76.94 means 76.94%.

Each font is { unitsPerEm, xWidthAvg, ascent, descent, lineGap }, in font units, as Capsize's metrics give them. unitsPerEm is the size of the grid the font is drawn on, often 1000 or 2048; xWidthAvg is its average character width, weighted by how often each letter appears in English; ascent, descent, and lineGap are the room above the baseline, below it, and between lines. The descent may be stored as a negative number, since it's below the baseline; its override is always positive.

These are the rules Capsize and fontaine use. Compare widths per em: sizeAdjust is the web font's xWidthAvg / unitsPerEm divided by the fallback's. The overrides are shares of the size the fallback is drawn at, which sizeAdjust has already scaled: each is the web font's ascent, the size of its descent, or its line gap, divided by the web font's unitsPerEm times sizeAdjust (as a share, not a percentage). Only the web font's vertical metrics count; the fallback's own ascent, descent, and line gap change nothing. Round each share times 100 to two decimal places.

fallbackOverrides(
  { unitsPerEm: 1000, xWidthAvg: 343, ascent: 960, descent: -300, lineGap: 0 }, // Caveat
  { unitsPerEm: 2048, xWidthAvg: 913, ascent: 1854, descent: -434, lineGap: 67 }, // Arial
);
// { sizeAdjust: 76.94, ascentOverride: 124.77, descentOverride: 38.99, lineGapOverride: 0 }
Write this: solution.js
function fallbackOverrides(webFont, fallbackFont) {
  // Today: the overrides alone, with the fallback drawn at its own size.
  const percent = (share) => Math.round(share * 10000) / 100;
  return {
    sizeAdjust: 100,
    ascentOverride: percent(webFont.ascent / webFont.unitsPerEm),
    descentOverride: percent(webFont.descent / webFont.unitsPerEm),
    lineGapOverride: percent(webFont.lineGap / webFont.unitsPerEm),
  };
}
The tests your code must pass
  • Caveat over Arial gives the numbers the font tools write
  • compares widths per em, so fonts drawn on different grids compare fairly
  • a descent stored as a negative number gives the same positive override
  • the line gap is scaled like the ascent and the descent
  • only the fallback's width counts, not its own heights
  • a fallback that is the same font needs no scaling, only its own metrics

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…