Functional Weave
Code in TypeScript

money.compare@1.0.0

impl/python.py

1,088 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 .math_clamp import clamp  ← from math.clamp ^1.0.0 · built alongside by fune
from .money_amount import Money, assert_same_currency, money  ← from money.amount ^1.0.0 · built alongside by fune


def compare_money(a: Money, b: Money) -> int:
    """-1, 0 or 1, comparing two amounts of the same currency.

    Refuses mixed currencies: which of GBP 10 and EUR 10 is larger depends on a
    rate, and a comparison that ignores the currency sorts a list into nonsense.
    """
    assert_same_currency(a, b)
    return -1 if a.minor < b.minor else 1 if a.minor > b.minor else 0


def min_money(a: Money, b: Money) -> Money:
    """The smaller amount; the first when they are equal."""
    return b if compare_money(b, a) < 0 else a


def max_money(a: Money, b: Money) -> Money:
    """The larger amount; the first when they are equal."""
    return b if compare_money(b, a) > 0 else a


def clamp_money(amount: Money, min: Money, max: Money) -> Money:  # noqa: A002
    """``amount`` held within ``min..max``, all three in one currency."""
    assert_same_currency(amount, min)
    assert_same_currency(amount, max)
    return money(clamp(amount.minor, min.minor, max.minor), amount.currency)