completefrontend

Write the codeEasy

Write a function that returns the share of good samples.

Every page of Leaf and Kettle sends each metric the web-vitals library reports to the shop's server as a beacon, { id, name, value }. Write goodShare(beacons, name), which returns the share of page loads whose name metric was good, from 0 to 1. beacons are in the order the pages sent them, and name is one of "LCP", "INP", "CLS", "FCP", and "TTFB".

A value is good when it's at or below the metric's good threshold in web-vitals: 2500 ms for LCP, 200 ms for INP, 0.1 for CLS, 1800 ms for FCP, and 800 ms for TTFB. One page load can send the same metric more than once: web-vitals reports CLS and INP again whenever the page is hidden and the value has changed, with the same id each time. Count each id once, with the value of its last beacon. Ignore beacons for other metrics, and return null when there are none for name.

goodShare(
  [
    { id: "v5-1", name: "LCP", value: 1900 },
    { id: "v5-2", name: "CLS", value: 0.04 },
    { id: "v5-3", name: "CLS", value: 0.08 },
    { id: "v5-2", name: "CLS", value: 0.16 }, // the same page load, hidden again after more shifts
  ],
  "CLS",
);
// 0.5: two page loads sent CLS, and only v5-3's last value is good
Write this: solution.js
// web-vitals' good thresholds: a value at or below one is good.
const GOOD = { LCP: 2500, INP: 200, CLS: 0.1, FCP: 1800, TTFB: 800 };
 
function goodShare(beacons, name) {
  // Today every beacon counts as a page load of its own.
  const samples = beacons.filter((beacon) => beacon.name === name);
  return samples.filter((beacon) => beacon.value <= GOOD[name]).length / samples.length;
}
The tests your code must pass
  • the share of good LCP loads, with a value right on the threshold counted as good
  • counts only the beacons for the metric it's asked about
  • a page load that sent CLS twice counts once, with its last value
  • the last beacon counts even when INP went down
  • FCP and TTFB have thresholds of their own
  • no beacons for the metric is null

Try it in the editor

The answer

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

Checking your sign-in…