Functional Weave
Code in Python

todo.sort@1.0.0

impl/python.py

2,568 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Any, Dict, List, Sequence, Tuple

from .collections_search_text import fold_ascii  ← from collections.search-text ^1.0.0 · built alongside by fune
from .collections_sort_by import sort_by  ← from collections.sort-by ^1.0.0 · built alongside by fune
from .collections_sort_by_types import SortDirection
from .todo_item import Todo  ← from todo.item ^1.0.0 · built alongside by fune
from .todo_item_validate_todo import is_utc_timestamp
from .todo_sort_types import TodoSortKey

_RANKS = {"none": 0, "low": 1, "medium": 2, "high": 3}

# Sort passes, least significant first; the last is the primary key and takes the direction.
_PASSES: Dict[str, Tuple[Tuple[str, str], ...]] = {
    "manual": (("created", "asc"), ("order", "dir")),
    "due": (("order", "asc"), ("rank", "desc"), ("due", "dir")),
    "priority": (("order", "asc"), ("due", "asc"), ("rank", "dir")),
    "created": (("order", "asc"), ("created", "dir")),
    "title": (("order", "asc"), ("title", "dir")),
}


def _rank(priority: str) -> int:
    if priority not in _RANKS:
        raise ValueError(f'unknown priority "{priority}": expected none, low, medium or high')
    return _RANKS[priority]


def _created_key(created_at: str) -> str:
    """A creation time that sorts as text: the fraction padded to nine digits."""
    if not is_utc_timestamp(created_at):
        raise ValueError(f'createdAt "{created_at}" is not a UTC timestamp, e.g. 2026-09-28T09:30:00Z')
    fraction = created_at[20:-1] if len(created_at) > 20 else ""
    return created_at[:19] + "." + fraction.ljust(9, "0")


def sort_todos(todos: Sequence[Todo], by: TodoSortKey, direction: SortDirection) -> List[Todo]:
    """Todos in list order for the chosen key: stable, direction on the primary key only."""
    if not isinstance(by, str) or by not in _PASSES:
        raise ValueError(f'unknown sort key "{by}": expected manual, due, priority, created or title')
    if direction not in ("asc", "desc"):
        raise ValueError(f'direction must be "asc" or "desc", received "{direction}"')
    passes = _PASSES[by]
    used = {field for field, _ in passes}
    records: List[Dict[str, Any]] = []
    for i, todo in enumerate(todos):
        r: Dict[str, Any] = {"i": i, "order": todo.order}
        if "created" in used:
            r["created"] = _created_key(todo.created_at)
        if "rank" in used:
            r["rank"] = _rank(todo.priority)
        if "due" in used:
            r["due"] = todo.due
        if "title" in used:
            r["title"] = fold_ascii(todo.title)
        records.append(r)
    for field, d in passes:
        records = sort_by(records, field, direction if d == "dir" else d)  # type: ignore[assignment]
    return [todos[r["i"]] for r in records]