"""Manual ordering of sibling rows with "Move up" / "Move down" buttons (specification 16.3).""" from collections.abc import Sequence from enum import StrEnum from apps.catalog.domain.exceptions import CannotMove class Direction(StrEnum): UP = "up" DOWN = "down" def move(ids: Sequence[int], item_id: int, direction: Direction) -> list[int]: """Return ``ids`` with ``item_id`` swapped with its neighbour in ``direction``.""" order = list(ids) index = order.index(item_id) target = index - 1 if direction is Direction.UP else index + 1 if not 0 <= target < len(order): raise CannotMove() order[index], order[target] = order[target], order[index] return order