From 071ffefffd18534c0a8d5a53349fc85256bc2419 Mon Sep 17 00:00:00 2001 From: Manav Rathi Date: Tue, 4 Feb 2025 11:52:40 +0530 Subject: [PATCH] Ensure ordering --- web/packages/base/i18n-date.ts | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/web/packages/base/i18n-date.ts b/web/packages/base/i18n-date.ts index dcf04aca9c..534dce5547 100644 --- a/web/packages/base/i18n-date.ts +++ b/web/packages/base/i18n-date.ts @@ -9,14 +9,15 @@ import i18n from "i18next"; let _relativeDateFormat: Intl.RelativeTimeFormat | undefined; export const formatDateRelative = (date: Date) => { - const units = { - year: 24 * 60 * 60 * 1000 * 365, - month: (24 * 60 * 60 * 1000 * 365) / 12, - day: 24 * 60 * 60 * 1000, - hour: 60 * 60 * 1000, - minute: 60 * 1000, - second: 1000, - }; + const units: [Intl.RelativeTimeFormatUnit, number][] = [ + ["year", 24 * 60 * 60 * 1000 * 365], + ["month", (24 * 60 * 60 * 1000 * 365) / 12], + ["day", 24 * 60 * 60 * 1000], + ["hour", 60 * 60 * 1000], + ["minute", 60 * 1000], + ["second", 1000], + ]; + const relativeDateFormat = (_relativeDateFormat ??= new Intl.RelativeTimeFormat(i18n.language, { localeMatcher: "best fit", @@ -24,13 +25,13 @@ export const formatDateRelative = (date: Date) => { style: "short", })); - // "Math.abs" accounts for both past and future scenarios. + // Math.abs accounts for both past and future scenarios. const elapsed = Math.abs(date.getTime() - Date.now()); - for (const u in units) - if (elapsed > units[u] || u === "second") - return relativeDateFormat.format( - Math.round(elapsed / units[u]), - u as Intl.RelativeTimeFormatUnit, - ); + for (const [u, d] of units) { + if (elapsed > d) + return relativeDateFormat.format(Math.round(elapsed / d), u); + } + + return relativeDateFormat.format(Math.round(elapsed / 1000), "second"); };