From 42066f9ddecbb5e3e790d55dfff96a0014c1fd7f Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Wed, 13 Nov 2024 14:31:35 +0000 Subject: [PATCH] Refactor --- agenda/utils.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/agenda/utils.py b/agenda/utils.py index 974f554..0c17610 100644 --- a/agenda/utils.py +++ b/agenda/utils.py @@ -42,6 +42,11 @@ def timedelta_display(delta: timedelta) -> str: ) +def plural(value: int, unit: str) -> str: + """Value + unit with unit written as singular or plural as appropriate.""" + return f"{value} {unit}{'s' if value > 1 else ''}" + + def human_readable_delta(future_date: date) -> str | None: """ Calculate the human-readable time delta for a given future date. @@ -64,14 +69,11 @@ def human_readable_delta(future_date: date) -> str | None: weeks, days = divmod(days, 7) # Formatting the output - parts = [] - if months > 0: - parts.append(f"{months} month{'s' if months > 1 else ''}") - if weeks > 0: - parts.append(f"{weeks} week{'s' if weeks > 1 else ''}") - if days > 0: - parts.append(f"{days} day{'s' if days > 1 else ''}") - + parts = [ + plural(value, unit) + for value, unit in ((months, "month"), (weeks, "week"), (days, "days")) + if value > 0 + ] return " ".join(parts) if parts else None