DEV Community

Daniel Pertu
Daniel Pertu

Posted on

Three time formatters in 28 lines, three clocks driving them, and the branches inside them no caller can reach

Notifio watches rental search pages and tells you the moment something new appears, which makes every timestamp in its window a claim about the product. "just now" under a listing is the pitch. "checked 4m ago" is either reassurance or an admission, depending on the number.

All of those strings come out of one file:

$ wc -l src/renderer/format.ts
28 src/renderer/format.ts
Enter fullscreen mode Exit fullscreen mode

Twenty-eight lines, three exported functions, five call sites. I went through all of it, because a formatter is the kind of code nobody reviews twice and every user reads constantly.

The three functions

/** "12s ago", "4m ago", "2h ago". Empty string for a null timestamp. */
export function relativeTime(at: number | null): string {
  if (!at) return "";
  const seconds = Math.max(0, Math.round((Date.now() - at) / 1000));
  if (seconds < 10) return "just now";
  if (seconds < 60) return `${seconds}s ago`;
  const minutes = Math.round(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.round(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  return `${Math.round(hours / 24)}d ago`;
}
Enter fullscreen mode Exit fullscreen mode

countdown(until) returns "any moment", "in 45s" or "in 3m", and seconds(ms) returns "1.4s". That is the whole module.

Round, not floor

Every band uses Math.round. The convention almost everywhere else, including GitHub, Slack and every timeago library I have read, is Math.floor: "2m ago" means at least two minutes have passed. Rounding to nearest means the number is the closest label rather than a lower bound, and that changes what each string can mean:

actual age     our label      floor would say
---------------------------------------------
9.4s           just now       just now
9.5s           10s ago        just now
70s            1m ago         1m ago
89s            1m ago         1m ago
90s            2m ago         1m ago
45m            45m ago        45m ago
90m            2h ago         1h ago
35h            1d ago         1d ago
36h            2d ago         1d ago
Enter fullscreen mode Exit fullscreen mode

The error is bounded at half a unit of whatever band you are in, which is 30 seconds in the minutes band, 30 minutes in the hours band and 12 hours in the days band. So "2d ago" on a find covers anything from 36 to 60 hours old.

Is round wrong here? For the hours and days bands I think it is better than floor: a check that ran 59 minutes ago reading "1h ago" is a more useful summary than "59m ago", and nobody is making decisions on the difference. For the seconds and minutes bands it is the wrong direction for this product specifically. "1m ago" that might mean 89 seconds is a claim about freshness that the app cannot support, and freshness is the only thing anybody buys this for. Those two bands are getting a floor.

Three clocks, three intervals

None of these strings would ever update on their own, because Date.now() is read during render. So there is a clock:

export function useNow(intervalMs = 1000, active = true): number {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    if (!active) return;
    const timer = setInterval(() => setNow(Date.now()), intervalMs);
    return () => clearInterval(timer);
  }, [intervalMs, active]);
  return now;
}
Enter fullscreen mode Exit fullscreen mode

Two parameters, both with defaults, and three call sites that override both:

useNow(5000, isActive);                                   // MonitorCard
useNow(30_000, app.finds.length > 0);                     // RecentFinds
useNow(1000, hasCountdown || app.status === "polling");    // SitesList
Enter fullscreen mode Exit fullscreen mode

The defaults have never been used. What I like about this list is that each interval was chosen for the most urgent string on that screen, and each active flag is a real condition rather than true spelled differently: the finds list stops ticking when there are no finds, the monitor card stops when the monitor is idle, the search list ticks every second only while something is counting down or a poll is in flight. An app sitting in the tray overnight runs no timers at all.

What I had not noticed is that two of the three intervals are coarser than the strings they drive.

relativeTime resolves to one second for the first minute of a timestamp's life. On the finds list, that formatter is driven by a 30 second clock:

{find.siteName} ยท {relativeTime(find.foundAt)}
Enter fullscreen mode Exit fullscreen mode

A find arrives, the data changes, the row renders, and the label says "just now". That stops being true at ten seconds. The next tick is up to thirty seconds away. So for up to twenty seconds, a listing that is half a minute old says "just now" on the screen whose entire job is to tell you how fresh things are. The monitor card has the milder version of the same thing: a 5 second clock under a label that counts in seconds, so "last check 12s ago" becomes "17s ago" in one jump.

Neither is a bug in the sense of being wrong on purpose. Both are the consequence of picking the interval per screen and the formatter per field, and never comparing the two. The fix is not a faster clock, because re-rendering a list once a second to keep a word honest for twenty seconds is a bad trade on a laptop battery. The fix is that a 30 second clock should drive a formatter whose smallest unit is a minute, which for the finds list means "just now" should last a minute rather than ten seconds.

Three branches no caller can reach

relativeTime starts with a null guard, and seconds ends with one:

if (!at) return "";
if (ms === null) return "";
Enter fullscreen mode Exit fullscreen mode

Both return an empty string, and both are documented in the JSDoc above the function. All five call sites guard first:

if (lastCheckedAt) summary.push(`last check ${relativeTime(lastCheckedAt)}`);
Enter fullscreen mode Exit fullscreen mode
} else if (runtime?.lastCheckedAt) {
  if (runtime.listingCount !== null) detail.push(`${runtime.listingCount} listings`);
  detail.push(`checked ${relativeTime(runtime.lastCheckedAt)}`);
  if (runtime.lastDurationMs !== null) detail.push(seconds(runtime.lastDurationMs));
}
Enter fullscreen mode Exit fullscreen mode

So neither empty string has ever been produced. That is the correct outcome and the guards should stay, because the alternative is a row reading "checked " with nothing after it, and a formatter that cannot be called wrongly is worth two lines. But it is worth knowing that the defensive branch is defending against callers that do not exist.

The third one is better. countdown opens with:

const ms = until - Date.now();
if (ms <= 0) return "any moment";
Enter fullscreen mode Exit fullscreen mode

Its one call site is the retry chip on a waiting search, and the value it passes was computed a few lines earlier in the same render:

const waiting =
  runtime?.nextRetryAt && runtime.nextRetryAt > Date.now() ? runtime.nextRetryAt : null;
Enter fullscreen mode Exit fullscreen mode

waiting is non-null only when the deadline is in the future. For countdown to see ms <= 0, the deadline has to pass between that comparison and the call, which are microseconds apart in the same synchronous render. "any moment" is not dead code in the strict sense, it is code whose window is one render pass wide. A user will never see it, and it is two words I would keep anyway, because the alternative when it does fire is "in 0s", and the chip it sits in is a button you can press to skip the wait.

The formatter with no bounds at all

/** "1.4s". Shown on a row so a slow site is visible rather than guessed at. */
export function seconds(ms: number | null): string {
  if (ms === null) return "";
  return `${(ms / 1000).toFixed(1)}s`;
}
Enter fullscreen mode Exit fullscreen mode

One decimal place, always, with no floor and no unit switch. Anything under 50ms renders as "0.0s", which reads as a check that did not happen. Anything slow renders in seconds forever: a check that took five minutes is "300.0s" rather than "5m". Neither end is reachable today, because the number it formats is the duration of a page load and those land between about half a second and a minute, but both are one product change away from being on screen.

That is the general lesson I am taking from 28 lines of formatting. The rounding mode, the clock interval and the unit ceiling are all invisible decisions that each have exactly one visible consequence, and all three of them were made once, in a hurry, by whoever needed a string that afternoon. They are worth an hour of someone's attention, because unlike most of the code in an app they are read by the user every single time they look at it.

You can see all three formatters in the running app from the download page, and the help page explains the thirty second poll that every one of these timestamps is measuring against.

Top comments (0)