Functional Weave
Code in TypeScript

money.compare@1.0.0

impl/typescript.ts

1,098 bytes · the TypeScript 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.

import { clamp } from "./math_clamp.ts";  ← from math.clamp ^1.0.0 · built alongside by fune
import { type Money, assertSameCurrency, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune

/**
 * -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.
 */
export function compareMoney(a: Money, b: Money): number {
  assertSameCurrency(a, b);
  return a.minor < b.minor ? -1 : a.minor > b.minor ? 1 : 0;
}

/** The smaller amount; the first when they are equal. */
export function minMoney(a: Money, b: Money): Money {
  return compareMoney(b, a) < 0 ? b : a;
}

/** The larger amount; the first when they are equal. */
export function maxMoney(a: Money, b: Money): Money {
  return compareMoney(b, a) > 0 ? b : a;
}

/** `amount` held within `min..max`, all three in one currency. */
export function clampMoney(amount: Money, min: Money, max: Money): Money {
  assertSameCurrency(amount, min);
  assertSameCurrency(amount, max);
  return money(clamp(amount.minor, min.minor, max.minor), amount.currency);
}