Functional Weave
Code in Python

math.clamp@1.0.0

impl/python.py

657 bytes · the Python implementation · view raw

def clamp(value: int, min: int, max: int) -> int:  # noqa: A002 - the manifest names them min and max
    """Clamp ``value`` to the inclusive range ``min..max``.

    Swapped bounds raise: ``max(lo, min(value, hi))`` would answer ``lo`` for
    everything and hide the bug that swapped them.
    """
    for v in (value, min, max):
        if isinstance(v, bool) or not isinstance(v, int):
            raise TypeError("clamp operates on integers only")
    if min > max:
        raise ValueError("min must not be greater than max (min %d, max %d)" % (min, max))
    if value < min:
        return min
    if value > max:
        return max
    return value