Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
"""Small helpers shared by the ledger modules."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, timedelta
|
|
from typing import Callable, Dict, Hashable, Iterable, Iterator, List, Sequence, TypeVar, Union
|
|
|
|
T = TypeVar("T")
|
|
K = TypeVar("K", bound=Hashable)
|
|
|
|
|
|
def chunked(items: Sequence[T], size: int) -> Iterator[Sequence[T]]:
|
|
"""Yield consecutive slices of ``items`` with at most ``size`` elements."""
|
|
if size < 1:
|
|
raise ValueError("size must be positive")
|
|
for start in range(0, len(items), size):
|
|
yield items[start:start + size]
|
|
|
|
|
|
def group_by(items: Iterable[T], key: Callable[[T], K]) -> Dict[K, List[T]]:
|
|
"""Group items by ``key`` keeping first-seen order of keys and items."""
|
|
groups: Dict[K, List[T]] = {}
|
|
for item in items:
|
|
groups.setdefault(key(item), []).append(item)
|
|
return groups
|
|
|
|
|
|
def ensure_date(value: Union[str, date]) -> date:
|
|
"""Accept a ``date`` or an ISO ``YYYY-MM-DD`` string."""
|
|
if isinstance(value, date):
|
|
return value
|
|
return date.fromisoformat(value)
|
|
|
|
|
|
def days_in_month(year: int, month: int) -> int:
|
|
start = date(year, month, 1)
|
|
following = date(year + (month == 12), month % 12 + 1, 1)
|
|
return (following - start).days
|
|
|
|
|
|
def first_of_month(d: date) -> date:
|
|
return d.replace(day=1)
|
|
|
|
|
|
def last_of_month(d: date) -> date:
|
|
return d.replace(day=days_in_month(d.year, d.month))
|
|
|
|
|
|
def add_months(d: date, months: int) -> date:
|
|
"""Shift ``d`` by whole months, clamping the day to the end of the target month."""
|
|
year, month0 = divmod(d.year * 12 + d.month - 1 + months, 12)
|
|
month = month0 + 1
|
|
return date(year, month, min(d.day, days_in_month(year, month)))
|
|
|
|
|
|
def daterange(start: date, end: date) -> Iterator[date]:
|
|
"""Every date from ``start`` to ``end`` inclusive."""
|
|
current = start
|
|
while current <= end:
|
|
yield current
|
|
current += timedelta(days=1)
|
|
|
|
|
|
def clamp(value, low, high):
|
|
return max(low, min(value, high))
|